python如何访问私有变量_python – 从类访问私有模块变量

我正在尝试理解python范围规则.为此,我尝试从同一模块中的类访问“非常私有”变量

bar = "bar"

_bar = "underscore"

__bar = "double underscore"

def foo():

print bar

print _bar

print globals()["__bar"]

print __bar

class Foo:

def __init__(self):

print bar

print _bar

print globals()["__bar"]

print __bar #NameError: global name '_Foo__bar' is not defined

foo()

Foo()

它因NameError而失败.我在规范中找不到任何相关内容.那么,为什么它失败了,这种行为描述的地方呢?

解决方法:

在类定义中,所有以双下划线开头的名称都会被破坏;重写以包含类名作为前缀.

这是一个支持在类中将名称标记为“私有”并保护它不被子类覆盖的功能.见identifiers documentation:

Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name, with leading underscores removed and a single underscore inserted, in front of the name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.

最好不要在模块全局变量上使用双下划线前缀;没有必要这样做,单个下划线足以表明该值是模块内部的.

如果您遇到这样的值,请创建一个未损坏的别名,或使用globals()[name].

标签:python,python-2-7,oop,private

来源: https://codeday.me/bug/20191007/1864524.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值