1

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?

Community
  • 1
  • 1
Eleutetio
  • 139
  • 2
  • 8

2 Answers2

2

The text you're quoting is, at best, confusing and misleading. But here is an example.

class A(object):
    def p(self):
       print(self)

 a1 = A()        # create two instances
 a2 = A()
 a1.p()          # calls A.p(a1); self is a1
 a2.p()          # calls A.p(a2); self is a2

What the second sentence means is that self is a reference to the object you are calling the method on: the object before the .. a1.p() is the same as A.p(a1) and the method is passed a1 for self.

The reason I said what you quoted is misleading is that it implies that __init__() is different from other methods. It's not. __init__() is a method like any other. It is automatically passed the instance it is to operate on as its first argument. It's just that it doesn't yet have a name when __init__() is called, because it's not given a name until it has been initialized. But self is still the instance.

The one that's really different is __new__(), but you will probably not need it for a while, if ever.

kindall
  • 178,883
  • 35
  • 278
  • 309
1

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.

Jordan McQueen
  • 777
  • 5
  • 10