+ 4

Please clarify the oop statement and use of __init__?

Class A: def __init__ (self): self.a=0 def change(self,n): a=n obj=A() obj.change(2) print(obj.a)

8th Jun 2020, 9:08 AM
《A$# ☆ $ING#》
《A$# ☆ $ING#》 - avatar
2 Answers
+ 1
init is basically loading up a class instance with default (or not) values
8th Jun 2020, 9:25 AM
Slick
Slick - avatar
+ 1
The __init__ function from the name itself you can see that it initializes the instance variables of a class. In __init__(self): here self is nothing but a reference to the current instance. When you say, obj = A() you are by default passing the instance 'obj' to the function. It is equivalent to obj = A(obj). So self.a is associated to an instance but the one in change() is not. It is a new variable. So when you say print(obj.a) it returns the one which is associated with the current instance 'obj'. You can do self.a = n in the change() to get the output as 2.
8th Jun 2020, 10:36 AM
Avinesh
Avinesh - avatar