Purpose of return self python

前端 未结 2 2001
名媛妹妹
名媛妹妹 2020-12-24 07:30

I have a problem with return self

class Fib: 
    def __init__(self, max):
        self.max = max
    def __iter__(self): 
        self.a = 0
           


        
2条回答
  •  春和景丽
    2020-12-24 08:13

    This is needlessly complex code. Pay little attention to it. There's no reason on earth to implement it this way.

    That being said, what it does is this:

    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
    

    This is all much easier to express as:

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

    Examples:

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

提交回复
热议问题