python 类私有变量和一般变量的区别_python – 私有变量和类本地引用

在第9.6节私人变量和类别 – 地方参考文献中,最后一段指出:

Notice that code passed to exec, eval() or execfile() does not

consider the classname of the invoking class to be the current class;

this is similar to the effect of the global statement, the effect of

which is likewise restricted to code that is byte-compiled together.

The same restriction applies to getattr(), setattr() and delattr(), as

well as when referencing dict directly.

这个文本完全没有任何意义.请解释或给我一些例子来证明这个想法.

解决方法:

想象一下,你有一个私人成员的班级:

class Foo:

__attr= 5

在类中,此属性可以作为__attr引用:

class Foo:

__attr= 5

print(__attr) # prints 5

但不是课外:

print(Foo.__attr) # raises AttributeError

但是如果在类中使用eval,exec或execfile则会有所不同:

class Foo:

__attr= 5

print(__attr) # prints 5

exec 'print(__attr)' # raises NameError

您引用的段落对此进行了解释. exec不认为Foo是“当前类”,因此不能引用private属性(除非您将其引用为Foo._Foo__attr).

标签:python,reference,private,local,class

来源: https://codeday.me/bug/20190628/1310571.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值