繁体   English   中英

即使没有类实例/对象,类中的打印语句也会被执行

[英]Print statement in class getting executed even though there is no class instance/object

我的python文件的内容

class myclass(object):
    def __init__(self):
        pass
    def myfun(self):
        pass
    print ("hello world")

执行文件输出

hello world

询问

since I did not create object of class . How's it still able to print "hello world" 

类主体在类定义时执行,这就是设计语言的方式。

从第9.3.1节“ 类定义”语法开始:

在实践中,类定义中的语句通常是函数定义,但是其他语句也是允许的,有时是有用的。

这就是执行模型在Python中的工作原理,因此无需多说。

根据我的理解...任何类都无法运行,直到我们通过创建对象来调用它

简直是误会。 这适用于def ,即功能块,但不适用于类块。

它会接到一个电话,因为python就是这样。 您的代码将始终返回输出。

你好,世界

class myclass(object):
    def __init__(self):
        pass

    def myfun(self):
        print("hello world")
        pass

如果要避免这种情况,则必须在方法内部添加print语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM