Python 即使没有类实例/对象,也要执行类中的Print语句
我的python文件的内容Python 即使没有类实例/对象,也要执行类中的Print语句,python,Python,我的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" 类主体在
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"
类主体在类定义时执行,这就是语言的设计方式 从第节语法: 实际上,类定义中的语句通常是函数定义,但允许使用其他语句,有时也很有用 这就是Python中执行模型的工作方式,因此没有更多的内容要说 根据我的理解…任何类都不能运行,除非我们通过创建一个对象来调用它
只是一个误会。这适用于
def
,即函数块,但不适用于类块。它将得到一个调用,因为python就是这样工作的。
您的代码将始终返回输出
你好,世界
class myclass(object):
def __init__(self):
pass
def myfun(self):
print("hello world")
pass
如果要避免这种情况,必须在方法中添加print语句 类中的任何内容都是运行的,就像它在基本缩进级别一样。它是特定于python的吗?根据我的理解…任何类都不能运行,除非我们通过创建一个对象来调用它