用以返回class的信息,还有__repr__()
用于循环
设定未出现的属性
直接对实例进行调用
class foo():
def __init__(self):
self.a = 0
self.b = 1
def __str__(self):
return("foo")
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > 10000:
raise StopIteration()
else:
return self.a
def __getitem__(self, sli):
if isinstance(sli, int):
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
if isinstance(sli, slice):
start = slice.start
stop = slice.stop
if start is None:
start = 0
a, b = 1, 1
L = []
for x in range(stop):
if x >= start:
L.append(a)
a, b = b, a + b
return L
def __getattr__(self, attr):
if attr=='attr':
return "fib"
raise AttributeError('\'foo\' object has no attribute \'%s\'' % attr)