@score.setter defscore(self, value): ifnottype(value) == int: raise ValueError('score must be an integer!') elif value < 0or value > 100: raise ValueError('score must between 0 ~ 100!') else: self._score = value
p = Person() p.score = 200# score must between 0 ~ 100! p.score = '200'# score must be an integer! p.score = 90 print(p.score) # 90
classPerson: def__init__(self, name): self._name = name
print(Person('Michael')) # <__main__.Person object at 0x000001644DFB28D0>
classPerson: def__init__(self, name): self._name = name
def__str__(self): return'Person object name is {}'.format(self._name)
__repr__ = __str__
print(Person('Michael')) # Person object name is Michael
Person('Michael') # Person object name is Michael
__iter__ 和 __next__
果一个类想被用于 for … in 循环,类似 list 或 tuple,就必须实现一个 __iter__() 方法,该方法返回一个迭代对象,然后,Python 的 for 循环就会不断调用该迭代对象的 __next__() 方法拿到循环的下一个值,直到遇到 StopIteration 错误时退出循环。
Fib 实例虽然能作用于 for 循环,看起来和 list 有点像,但是,把它当成 list 来使用还是不行,比如,取第 5 个元素:
Fib()[5] # TypeError: 'Fib' object does not support indexing
要表现得像 list 那样按照下标取出元素,需要实现 __getitem__() 方法:
classFib(object): def__getitem__(self, n): ifisinstance(n, int): # n是索引 a, b = 1, 1 for 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