Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what gets returned when you return self?

what gets returned when you return 'self' inside a python class? where do we exactly use return 'self'? In the below example what does self exactly returns

class Fib:
'''iterator that yields numbers in the Fibonacci sequence'''

    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
        print(self.a,self.b,self.c)
        return fib
like image 707
Karthik Elangovan Avatar asked Nov 27 '25 07:11

Karthik Elangovan


2 Answers

Python treats method calls like object.method() approximately like method(object). The docs say that "call x.f() is exactly equivalent to MyClass.f(x)". This means that a method will receive the object as the first argument. By convention in the definition of methods, this first argument is called self.

So self is the conventional name of the object owning the method.

Now, why would we want to return self? In your particular example, it is because the object implements the iterator protocol, which basically means it has __iter__ and __next__ methods. The __iter__ method must (according to the docs) "Return the iterator object itself", which is exactly what is happening here.

As an aside, another common reason for returning self is to support method chaining, where you would want to do object.method1().method2().method3() where all those methods are defined in the same class. This pattern is quite common in libraries like pandas.

like image 72
chthonicdaemon Avatar answered Nov 29 '25 19:11

chthonicdaemon


The keyword self is used to refer to the instance that you are calling the method from.

This is particularly useful for chaining. In your example, let's say we want to call __next__() on an initialized Fib instance. Since __iter__() returns self, the following are equivalent :

obj = Fib(5)
obj.__iter__() # Initialize obj 
obj.__next__()

And

obj = Fib(5).__iter__() # Create AND initialize obj
obj.__next__()

In your particular example, the self keyword returns the instance of the Fib class from which you are calling __iter__() (called obj in my small snippet).

Hope it'll be helpful.

like image 41
3kt Avatar answered Nov 29 '25 21:11

3kt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!