1.API中相关描述
2.示例
1
num = 4
class Test:
num = 3
def f(self):
self.num += 2
print(self.num) # 5
num += 3 # UnboundLocalError: local variable 'num' referenced before assignment
print(num)
x = Test()
x.f()
'''
为什么self.num += 2正常执行,num += 3报错?
这里为方便,忽略增强赋值语句和普通赋值语句的差异,从普通赋值语句分析
既问题变为:为什么self.num = self.num + 2正常执行而num = num + 3报错?
1.对于类对象属性或实例对象的数据属性
1.右边的num可能是类属性或实例对象的数据属性
2.左边的num是实例的数据属性,在必要时会自动创建
2.对于普通变量
左右两边的num最终均会被解析为局部变量
'''
再来点补充知识:
9.2. Python Scopes and Namespaces
A special quirk of Python is that – if noglobal
statement is in effect – assignments to names always go into the innermost scope. Assignments do not copy data — they just bind names to objects. The same is true for deletions: the statement
del x
removes the binding of
x
from the namespace referenced by the local scope. In fact, all operations that introduce new names use the local scope: in particular,
import
statements and function definitions bind the module or function name in the local scope.