我对 return self
有疑问
class Fib:
def __init__(self, max):
self.max = max
def __iter__(self):
self.a = 0
self.b = 1
return self
def __next__(self):
fib = self.a
if fib > self.max:
raise StopIteration
self.a, self.b = self.b, self.a + self.b
return fib
这个问题我已经看过return self problem但我不明白 return self
有什么好处?
最佳答案
返回 self
来自方法只是意味着您的方法返回对调用它的实例对象的引用。这有时可以在与设计为 fluent interface 的面向对象的 API 一起使用时看到。鼓励method cascading .所以,例如,
>>> class Counter(object):
... def __init__(self, start=1):
... self.val = start
... def increment(self):
... self.val += 1
... return self
... def decrement(self):
... self.val -= 1
... return self
...
>>> c = Counter()
现在我们可以使用方法级联了:
>>> c.increment().increment().decrement()
<__main__.Counter object at 0x1020c1390>
注意,最后一次调用decrement()
返回 <__main__.Counter object at 0x1020c1390>
,是 self
.
现在:
>>> c.val
2
>>>
请注意,如果您没有返回 self
,您将无法执行此操作:
>>> class Counter(object):
... def __init__(self, start=1):
... self.val = start
... def increment(self):
... self.val += 1
... # implicitely return `None`
... def decrement(self):
... self.val -= 1
... # implicitely return `None`
...
>>> c = Counter()
>>> c.increment().increment()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'increment'
>>> c
<__main__.Counter object at 0x1020c15f8>
>>> c.val
2
>>>
请注意,并不是每个人都喜欢“方法级联”设计。 Python 内置函数不倾向于这样做,因此,list
例如:
>>> x = list()
>>> x.append(1).append(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'append'
>>>
你做经常看到的一个地方是你的类实现了iterator
协议(protocol),其中 iter
在迭代器上返回 self
按照惯例,虽然这是由 the docs 建议的:
Having seen the mechanics behind the iterator protocol, it is easy to add iterator behavior to your classes. Define an
__iter__()
method which returns an object with a__next__()
method. If the class defines__next__()
, then__iter__()
can just returnself
:class Reverse: """Iterator for looping over a sequence backwards.""" def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def __next__(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index]
注意,这实际上使您的迭代器仅对单次传递有用(因为它应该正确地遵循迭代器协议(protocol)):
>>> x = [1, 2, 3, 4]
>>> it = iter(x)
>>> list(it)
[1, 2, 3, 4]
>>> list(it)
[]
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
关于python - 返回 self python的目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43380042/