当我运行下面的代码时,输出是“hello”。
但是,print 语句是 pl 类的一部分,而我从未创建过 pl 类的实例,所以为什么print 语句正在执行?
class pl:
def __init__(self,a,b):
self.aa=a
self.bb=b
print("hello")
请您参考如下方法:
类主体(甚至嵌套类主体)在导入时执行(与函数或方法相反)。
演示脚本:
class Upper:
print('Upper')
class Mid:
print('Mid')
def method(self):
class Low:
print('Low')
print('method')
输出:
$ python3
>>> import demo
Upper
Mid
