【问题标题】:Why are statements in a Class executed without instantiation? [duplicate]为什么在没有实例化的情况下执行类中的语句? [复制]
【发布时间】:2020-09-10 09:25:31
【问题描述】:

我想了解python中类的以下行为:

class A:
   print("I am in class")

运行此代码后,无需创建任何实例,我就可以看到打印语句已执行。没有创建实例,为什么会执行这条语句?

【问题讨论】:

    标签: python python-3.x oop


    【解决方案1】:

    这是因为 Python 执行了类主体中的所有代码。

    如果您希望 print("I am in class") 仅在您创建实例时运行,请尝试以这种方式定义您的类,看看行为如何变化:

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

    补充一下,相信上一个问题的答案可以给你更多的细节:Why does a class' body get executed at definition time?

    【讨论】:

      猜你喜欢
      • 2013-03-14
      • 1970-01-01
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多