返回自我python的目的

时间:2017-04-12 21:36:24

标签: python return

我遇到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的好处是什么?

2 个答案:

答案 0 :(得分:12)

从方法返回self只是意味着您的方法返回对调用它的实例对象的引用。这有时可以在面向对象的API中使用,这些API被设计为鼓励fluent interfacemethod 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协议的时候,其中迭代器上的iter按惯例返回self,尽管这由the docs建议:

  

看过迭代器协议背后的机制,很容易   将迭代器行为添加到您的类中。定义__iter__()方法   返回一个带有__next__()方法的对象。如果上课   定义__next__(),然后__iter__()可以返回self

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]

注意,这实际上使得迭代器仅对单次传递有用:

>>> 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
>>>

答案 1 :(得分:1)

这是不必要的复杂代码。很少注意它。世界上没有理由以这种方式实施它。

话虽如此,它的作用是:

class Fib: 

    """Implements the Fibonacci sequence."""

    def __init__(self, max_):
        self.max = max_

    def __iter__(self):
        """Initializes and returns itself as an iterable."""

        self.a = 0
        self.b = 1
        return self

    def __next__(self):
        """What gets run on each execution of that iterable."""

        fib = self.a
        if fib > self.max:
            raise StopIteration
        self.a, self.b = self.b, self.a + self.b  # increment
        return fib

这更容易表达为:

def fib(max_):
    a, b = 0, 1
    while b <= max_:
        out = a
        a, b = b, a+b
        yield out

示例:

>>> fib_obj = Fib(20)
>>> for n in fib_obj:
...     print(n)

>>> for n in Fib(20):
...     print(n)

>>> for n in fib(20):
...     print(n)
# all give....
0
1
1
2
3
5
8
13