【问题标题】:Why statement in class gets called even without class access? [duplicate]为什么即使没有类访问权限也会调用类中的语句? [复制]
【发布时间】:2020-04-30 15:00:38
【问题描述】:

我将类声明和主脚本放在同一个模块中,发现虽然没有调用或实例化'My'类,但执行了'print'子句。

有人可以帮我理解为什么虽然我没有调用类“My”,但为什么会输出“This will be run”?

class My(): 


    print("This will be run") 

    def myout(self): 

        print("This will not be run")


if __name__ == '__main__': 


    print("Hello World")

预期输出:

你好世界

实际输出:

这将运行
你好世界

【问题讨论】:

  • 如果您将语句 print("This will be run") 换成 x = max(1,2) 之类的语句,可能对您更有意义
  • 始终对所有与 python 相关的问题使用通用 python 标签

标签: python python-3.x


【解决方案1】:

类对象是在您的脚本运行时创建的。这意味着类内的任何代码都将像在类外(在全局范围内)一样执行。为了创建你的类对象,解释器需要运行里面的所有代码(这就是你的"This will be run"字符串被打印的原因)。方法定义中的字符串没有运行,因为......嗯......它在一个方法中并且没有被调用。

对象必须在您引用它之前创建,因此主体中的代码必须在某个时候运行。唯一合理的运行时间是在创建类时。

class Test:
    print("Anything here will be run when 'Test' is first created.")
    print("Note: This isn't run when an *instance* is created.")
    print("Only when the class object is created")
    def test_method(self):
        print("test_method is never called so you won't see this.")

print(Test) # This will show something because the Test class object has been created.

输出:

Anything here will be run when 'Test' is first created.
Note: This isn't run when an *instance* is created.
Only when the class object is created
<class '__main__.Test'>

【讨论】:

    猜你喜欢
    • 2020-01-03
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多