I'm pretty new to OOP and I need some help understanding the need for a constructor in a python class.
I understand init is used to initialize class variables like below:
class myClass():
def __init__ (self):
self.x = 3
print("object created")
A = myClass()
print(A.x)
A.x = 6
print(A.x)
Output:
object created
3
6
but, I could also just do,
class myClass():
x = 3
print("object created")
A = myClass()
print(A.x)
A.x = 6
print(A.x)
which prints out the same result.
Could you please explain why we need a constructor or give me an example of a case when the above method will not work?
__init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor. The __init__ method can be called when an object is created from the class, and access is required to initialize the attributes of the class.
"__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.
The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__() , like this: def __init__(self): self.
It's not mandatory. But if you want the A. __init__ method to handle its own initialization and B. __init__() just something bit more, you wave to call it.
Citation: But I can also do
class myClass():
x = 3
print("object created")
A = myClass()
print(A.x)
A.x = 6
print(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
class MyClass:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With