Reputation: 133
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
Upvotes: 3
Views: 3947
Reputation: 19750
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.
Upvotes: 3
Reputation: 2553
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.
Upvotes: 1
Reputation: 2701
When you return self
, you return the class instance. For example:
class Foo:
def __init__(self, a):
self.a = a
def ret_self(self):
return self
If I create an instance and run ret_self
, you will see that they both refer to the same instance:
>>> x = Foo("a")
>>> x
<__main__.Foo instance at 0x0000000002823D48>
>>> x.ret_self()
<__main__.Foo instance at 0x0000000002823D48>
In other words, both x
and x.ret_self()
return the same reference to that class instance.
self
is actually another way of saying "this instance of Foo
". Hence, instance variables are self.a
in the class.
When will you need this? I don't have the experience to tell you and I do not want to give possibly misleading information that I am unsure of. I will leave it to someone else to expound on this answer.
Please do not accept this answer.
Upvotes: 0