Why Do We Need __init__ To Initialize A Python Class
Solution 1:
Citation: But I can also do
class myClass():
x = 3print("object created")
A = myClass()
print(A.x)
A.x = 6print(A.x)
No you cannot. There is a fundamental difference once you want to create two or more objects of the same class. Maybe this behaviour becomes clearer like this
classMyClass:
x = 3
print("Created!")
a = MyClass() # Will output "Created!"
a = MyClass() # Will output nothing since the class already exists!
In principle you need __init__ in order to write that code that needs to get executed for every new object whenever this object gets initialized / created - not just once when the class is read in.
Solution 2:
__init__
is used to initialize the state of multiple instances of a class where each instance's state is decoupled from each other, whereas your second example, without __init__
initializes an attribute that is shared among all instances of a class.
Solution 3:
init() is a default method which is called every time an object is created,so here the variables inside the init are called as instance attributes. the init() is called automatically every time an object is created, data you pass to object when it is created it gets assigned to the instance variables with the init() method here we are simply binding the method and the variables, and each object will have separate copy of these instance variables changing the data in one object will not effect it in another object
Post a Comment for "Why Do We Need __init__ To Initialize A Python Class"