类被执行而没有创建对象? 由 jsed发布于 2020-05-23 23:08:08 我想了解python中类的以下行为: class A: print("I am in class") 在运行此代码之后,没有创建任何实例,我可以看到执行了print #statement,因此,如果不创建实例,则#without如何执行该#statement?
发生这种情况是因为Python执行了类体中的所有代码。
If you want
print("I am in class")
to run only when you create an instance, try defining your class this way and see how the behaviour changes:Just to add on, I believe the answers to this previous question can give you more details: Why does a class' body get executed at definition time?