user8751232
user8751232

Reputation: 49

how self can be passed while inheritance?

class Trout(Fish):
    def __init__(self, water = "freshwater"):
        self.water = water
        super().__init__(self)

In this line super().__init__(self) how is the self parameter passed to the function?

Upvotes: 0

Views: 33

Answers (2)

Prune
Prune

Reputation: 77837

The object calling the method is implicitly (automatically) the first argument to the method. This is an agreement the language makes with itself.

In practical terms, assume you have an object obj of some type that has a method stuff that takes a simple Boolean argument. You invoke the method as

obj.stuff(True)

If this were a "normal" function, you would invoke it as

stuff(obj, True)

... but that's not how the syntax of classes and objects works. In any case, the function/method header looks the same:

def stuff(self, flag):

The difference here is that the each object class can have a method stuff, and we don't have to give them different names. When we use class methods, the compiler knows which one to use by looking at the class of the invoking object.


In the specific case of the __init__ method, the object is created immediately upon entry and assigned to self. This is another automatic agreement the language makes with itself: this specially-named function includes an invisible creation of a default object when you enter.

Upvotes: 0

chepner
chepner

Reputation: 530920

Say you have the code

f = Trout()

Behind the scenes, this is roughly equivalent to

f = Trout.__new__()
Trout.__init__(f)

Inside Trout.__init__, super() returns a proxy object that represents the appropriate class in the method resolution order of Trout; you don't actually have to pass self as an explicit argument; super().__init__ defaults to a bound method with self already present.

Upvotes: 1

Related Questions