Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need __init__ to initialize a python class

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?

like image 410
stedy Avatar asked Nov 15 '18 11:11

stedy


People also ask

Why is __ init __ important?

__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.

What is __ init __ In Python 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.

What does it mean to initialize a class in Python?

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.

Is __ init __ Mandatory?

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.


1 Answers

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.

like image 197
quant Avatar answered Sep 24 '22 07:09

quant