Python 面向对象编程深入解析
1. Python 变量作用域与命名空间
在 Python 中,变量作用域和命名空间是非常重要的概念。以下是一个示例代码,展示了不同作用域下变量的访问情况:
# otherfile.py
import manynames
X = 66
print(X) # 66: the global here
print(manynames.X) # 11: globals become attributes after imports
manynames.f() # 11: manynames's X, not the one here!
manynames.g() # 22: local in other file's function
print(manynames.C.X) # 33: attribute of class in other module
I = manynames.C()
print(I.X) # 33: still from class here
I.m()
print(I.X) # 55: now from instance!
从这个示例中可以看出,作用域是由源代码中赋值语句的位置决定的,不会受到导入关系的影响。并且,实例的属性在赋值时才会创建。
1.1 命名空间字典
在 Python 中,模块、类和实例对象的命名空间实际上都是以字典的形式实现的,通过 __dict__
属性可以访问。以下是一个交互式会话示例,展示了命名空间字典的增长过程: