Init and self


#1



what is the role of self here?
i mean that we created a function which created attriibutes- self, name & age
but what is going on in the code given below?


def __init__(self, name, age):
        self.name = name
        self.age = age

the name and age were same as self so how come they are being referred to as properties of self?
as in what does these statements do
self.name= name
self.age= age?


#2

Hi @systemjumper76679,

This header specifies three variables that are local to the __init__ method ...

    def __init__(self, name, age):

The variables are self, name, and age.

The role of self is to refer to the new instance of Animal that is being created.

Here, the properties name and age are created as part of that new instance. Although they have the same names as two of the local variables, they are different objects ...

        self.name = name
        self.age = age

This __init__ method would have had the same effect as the one you posted ...

    def __init__(self, n, a):
        self.name = n
        self.age = a

In the __init__ method, many programmers use the same name for parameters as they use for the instance variables the parameters are used to initialize, but they are different objects, and do not need to have the same names.


#3

The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self is the convention, and people will generally frown at you when you use something else.) self is not special to the code, it's just another object.

Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs self..

Learn Python here: https://hackr.io/tutorials/learn-python


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.