10

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?

3
  • You can read about class members vs instance members in python. This should improve your understandings. Commented Nov 15, 2018 at 11:33
  • You can pass arguments to the class object and assign those values to class members in the constructor. Commented Nov 15, 2018 at 11:34
  • 2
    Why do we use __init__ in Python classes? Commented Nov 15, 2018 at 11:36

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this helped my understanding!
5

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

1 Comment

Okay, my understanding became clearer.. Thank you :)
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.