Why do we need __init__ to initialize a python class

痞子三分冷 提交于 2020-05-11 10:27:59

问题


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?


回答1:


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 this 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 principal 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.




回答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.



来源:https://stackoverflow.com/questions/53318475/why-do-we-need-init-to-initialize-a-python-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!