类被执行而没有创建对象?

我想了解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:

class A:
     def __init__(self):
         print("I am in class A")

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?

点赞
评论