属性和普通变量使用增强赋值语句时的差异

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 no  global  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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值