python学习(八)定制类和枚举
`python`定制類主要是實現(xiàn)特定功能,通過在類中定義特定的函數(shù)完成特定的功能。
class Student(object):def __init__(self, name):self.name =namestudent = Student("lilei") print(student)`實現(xiàn)定制類`
class Student(object):def __init__(self, name):self.name = namedef __str__(self):return ("self name is %s" %(self.name))student2 = Student("hanmeimei") print(student2)?
實現(xiàn)`__str__`函數(shù),可以在print類對象時打印指定信息
通過實現(xiàn)`__iter__`和`__next__`同樣可以使類對象產(chǎn)生可迭代序列,下面實現(xiàn)了`斐波那契數(shù)列`
class Fib(object):def __init__(self):self.a , self.b = 0,1def __iter__(self):return selfdef __next__(self):self.a, self.b = self.b, self.a+ self.bf self.a > 30:raise StopIteration()return self.a打印輸出
for n in Fib():print(n)可以實現(xiàn)`__getitem__`函數(shù),這樣就可以按照索引訪問類對象中迭代元素了。
class OddNum(object):def __init__(self):self.num = -1def __iter__(self):return selfdef __next__(self):self.num = self.num +2if self.num > 10:raise StopIteration()return self.num def __getitem__(self,n):temp = 1for i in range(n):temp += 2return temp?
for n in OddNum():print(n)oddnum = OddNum() print(oddnum[3])?
?
可以進一步完善OddNum類的`__getitem__`函數(shù),使其支持`切片處理`
def __getitem__(self, n):if isinstance(n ,int):temp =1for i in range(n):temp +=2return tempif isinstance(n, slice):start = n.startend = n.stopif start is None:start = 0tempList = []temp = 1for i in range(end):if i >= start:temp += 2tempList.append(temp)return tempList?
`print(oddnum[1:4])`
通過實現(xiàn)`__getattr__`函數(shù),可以在類對象中沒有某個屬性時,自動調(diào)用`__getattr__`函數(shù)
實現(xiàn)`__call__`函數(shù),可以實現(xiàn)類對象的函數(shù)式調(diào)用
?
只有在沒有找到屬性的情況下,才調(diào)用`__getattr__`,已有的屬性不會在`__getattr__`中查找。
?
下面是廖雪峰官方網(wǎng)站上的一個鏈式轉(zhuǎn)化例子,用到了這些特定函數(shù)
?
?
class Chain(object):def __init__(self, path=''):self.path = pathdef __getattr__(self,attr):return Chain('%s/%s'%(self.path, attr))def __call__(self, param):return Chain('%s/%s'%(self.path, param))def __str__(self):return self.path__repr__ = __str__print(Chain().get.users('michael').group('doctor').repos)?
?
python同樣支持`枚舉`操作
from enum import EnumMonth = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))for name, member in Month.__members__.items():print(name, '=>', member, ',', member.value)from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec') ) for name, member in Month.__members__.items():print(name, '=>', member, ',', member.value)from enum import unique @unique class Weekday(Enum):Sun = 0 # Sun的value被設定為0Mon = 1Tue = 2Wed = 3Thu = 4Fri = 5Sat = 6for name , member in Weekday.__members__.items():print(name, '=>', member, ',', member.value)?
??
我的微信公眾號:
?
轉(zhuǎn)載于:https://www.cnblogs.com/secondtonone1/p/7458805.html
總結
以上是生活随笔為你收集整理的python学习(八)定制类和枚举的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: charset参数 sqluldr2_大
- 下一篇: HALCON示例程序measure_ri