Skip to content

Latest commit

 

History

History
30 lines (22 loc) · 557 Bytes

导入机制.md

File metadata and controls

30 lines (22 loc) · 557 Bytes

当从模块b导入a,运行b,会输出什么?

# a.py

print("a.py")

def f():
    print("a.f-函数变量")
    
class A:
    print("a.A-类变量")
    
    def ff(self):
        print("a.A.ff-类函数变量")
# b.py

import a

结果:

a.py
a.A-类变量

python模块导入时,会创建一个module对象,并插入到sys.module中,可以通过print dir(sys.modules['a'])查看模块属性。

模块中的顶层变量会在模块导入时就执行,类变量也是如此,函数会延迟生成。