Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 即使没有类实例/对象,也要执行类中的Print语句_Python - Fatal编程技术网

Python 即使没有类实例/对象,也要执行类中的Print语句

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" 类主体在

我的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" 

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

从第节语法:

实际上,类定义中的语句通常是函数定义,但允许使用其他语句,有时也很有用

这就是Python中执行模型的工作方式,因此没有更多的内容要说

根据我的理解…任何类都不能运行,除非我们通过创建一个对象来调用它


只是一个误会。这适用于
def
,即函数块,但不适用于类块。

它将得到一个调用,因为python就是这样工作的。 您的代码将始终返回输出

你好,世界

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

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

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

类中的任何内容都是运行的,就像它在基本缩进级别一样。它是特定于python的吗?根据我的理解…任何类都不能运行,除非我们通过创建一个对象来调用它