__str__ 和 __repr__ :实例对象直接显示字符串
class Student: def __init__(self, name): self.name = name def __str__(self): return "Name: %s" % self.name __repr__ = __str__
>>> s = Student("Zoro") >>> s Out[70]: Name: Zoro
# __str__()
返回用户看到的字符串,而__repr__()
返回程序开发者看到的字符串,也就是说,__repr__()
是为调试服务的。
__iter__ 和 __next__ : 实例对象能够用于迭代
class Fib: 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 > 1000: raise StopIteration return self.a
>>> f = Fib() >>> for i in f: ...: print(i, end=" ") ...: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
# __iter__()
方法返回一个迭代对象,然后Python的for循环就会不断调用该迭代对象的__next__()
方法拿到循环的下一个值,直到遇到StopIteration
错误时退出循环。
__getitem__ : 实例对象可以下标操作
class Fib: def __getitem__(self, n): a, b = 1, 1 for i in range(n): a, b = b, a+b return a
>>> f = Fib() >>> f[5] Out[97]: 8 >>> for i in range(20): print(f[i], end=" ") 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
__getattr__ : 访问不存在的属性时调用
class Student: def __getattr__(self, attr): if attr == "age": return 26 raise AttributeError("'Student' class has no attribute '%s!'" % attr)
>>> s = Student() >>> s.age Out[117]: 26 >>> s.name Traceback (most recent call last): File "<ipython-input-118-35e6ae75375b>", line 1, in <module> s.name File "C:/Users/SQD/Desktop/__getattr__.py", line 12, in __getattr__ raise AttributeError("'Student' class has no attribute '%s!'" % attr) AttributeError: 'Student' class has no attribute 'name!'
class Chain(object): def __init__(self, path=''): self._path = path def __getattr__(self, path): return Chain("%s/%s" % (self._path, path)) def __str__(self): return self._path __repr__ = __str__
>>> c = Chain() >>> c.status.user.timeline.list Out[130]: /status/user/timeline/list
__call__ : 直接对实例进行调用
class Student: def __init__(self, name): self._name = name def __call__(self): print("My name is %s" % self._name)
>>> s = Student("Zoro") >>> s() My name is Zoro