# 定制类
# ① __str__ ② __repr__()
class Student(object):
def __init__(self,name):
self.name = name
def __str__(self):
return 'Student object (name:%s)' % self.name
__repr__ = __str__
print(Student('pengyao'))
# Student object (name:pengyao) 有__str__的输出
# <__main__.Student object at 0x109afb190> 没有__str__的输出
# ③ __iter__ 以菲波那切数列数列为例
class Fib(object):
def __init__(self):
self.a,self.b = 0,1
def __iter__(self):
return self
def __next__(self):
self.a,self.b = self.b,self.a+self.b
if(self.a > 100):
raise StopIteration()
return self.a
# Fib()即Fib类的实例,实例化过程就包含了循环过程
print(list(Fib()))
# 输出:[1,1,2,3,5,8,13,21,34,55,89]
# 把Fib实例作用于for循环
for n in Fib():
print(n)
# ④ __getitem__
# Fib实例虽然能作用于for循环,看起来和list有点像,
# 但是,把它当成list来使用还是不行,比如,取第5个元素:
# print(Fib()[5]) #TypeError: 'Fib' object does not support indexing
# 要表现得像list那样按照下标取出元素,需要实现__getitem__()方法
class Fib4(object):
def __getitem__(self,n):
a,b = 1,1
for x in range(n):
a,b = b,a+b
return a
f = Fib4()
print(f[3]) # 3