__getitem__
使类表现像list那样按照下标取出元素
classFib(object):def__getitem__(self, n):
a, b =1,1for x inrange(n):
a, b = b, a + b
return a
>>> f = Fib()>>> f[0]1>>> f[1]1>>> f[2]2>>> f[3]3>>> f[10]89>>> f[100]573147844013817084101
切片功能不能使用,主要是需要对传入的参数进行判断
classFib(object):def__getitem__(self, n):ifisinstance(n,int):# n是索引
a, b =1,1for x inrange(n):
a, b = b, a + b
return a
ifisinstance(n,slice):# n是切片
start = n.start
stop = n.stop
if start isNone:
start =0
a, b =1,1
L =[]for x inrange(stop):if x >= start:
L.append(a)
a, b = b, a + b
return L
>>> f = Fib()>>> f[0:5][1,1,2,3,5]>>> f[:10][1,1,2,3,5,8,13,21,34,55]
__call__
任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用
通过callable()函数,我们就可以判断一个对象是否是“可调用”对象。
classStudent(object):def__init__(self, name):
self.name = name
def__call__(self):print('My name is %s.'% self.name)>>> s = Student('Michael')>>> s()# self参数不要传入
My name is Michael.
枚举类
枚举
from enum import Enum
Month = Enum('Month',('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'))
这样我们就获得了Month类型的枚举类,可以直接使用Month.Jan来引用一个常量
枚举类
from enum import Enum, unique
@unique
classWeekday(Enum):
Sun =0# Sun的value被设定为0
Mon =1
Tue =2
Wed =3
Thu =4
Fri =5
Sat =6
@unique装饰器可以帮助我们检查保证没有重复值。
>>> day1 = Weekday.Mon
>>>print(day1)
Weekday.Mon
>>>print(Weekday.Tue)
Weekday.Tue
>>>print(Weekday['Tue'])
Weekday.Tue
>>>print(Weekday.Tue.value)2>>>print(day1 == Weekday.Mon)True>>>print(day1 == Weekday.Tue)False>>>print(Weekday(1))
Weekday.Mon
>>>print(day1 == Weekday(1))True>>> Weekday(7)
Traceback (most recent call last):...
ValueError:7isnot a valid Weekday
>>>for name, member in Weekday.__members__.items():...print(name,'=>', member)...
Sun => Weekday.Sun
Mon => Weekday.Mon
Tue => Weekday.Tue
Wed => Weekday.Wed
Thu => Weekday.Thu
Fri => Weekday.Fri
Sat => Weekday.Sat