Eleutetio Eleutetio - 1 month ago 5
Python Question

self refers to the newly created object; in other class methods, it refers to the instance whose method was called.?

I am learning OOP in python and following this and this stackoverflow answers and this post

In the blog post writer explained this :


In the init method, self refers to the newly created object; in
other class methods, it refers to the instance whose method was
called.


I understood first part of this line , but couldn't understand second part of this line


"in other class methods, it refers to the instance whose method was
called."


What is the meaning of second line ? can someone please explain with explample?

Answer

Let's say you make a class:

class Rectangle():
    def __init__(self, height, width):
        self.height = height
        self.width = width

    def volume(self):
        return self.height * self.width

What they're saying isn't much really, it just sounds confusing.

Let's say we make a new Rectangle:

rect = Rectangle(5, 4)

In this case, self is referring to the newly created Rectangle rect.

If we call the volume method of rect...

print rect.volume()

Python will inject the object rect as the self variable, and use rects height and width. Since we called the volume method of rect, self refers to rect.

It might help to think of calling rect.volume() in these terms: Rectangle.volume(rect).

I believe the author was trying to explain the mechanism of self, but possibly made it a bit confusing.