M
M
Moro Zota2018-05-19 12:17:06
Python
Moro Zota, 2018-05-19 12:17:06

Why use __init__?

Why use __init__ when you can just set variables in the class ?

class A():
    var = 3
    def __init__(self, var2):
        self.var2 = var2

class B(A):
        def x(self):
            print(self.var)
            print(self.var2)


b = B(1)
print(b.x())

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Dergachov, 2018-05-19
@morozota

Variables in the class when creating an object will have the same value, and when initialized through a constructor, you can pass different values.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question