python双下划线函数debug=true,关于属性:Python双下划线修改

我对这种行为有点困惑(使用python 3.2):

class Bar:

pass

bar = Bar()

bar.__cache = None

print(vars(bar))        # {'__cache': None}

class Foo:

def __init__(self):

self.__cache = None

foo = Foo()

print(vars(foo))        # {'_Foo__cache': None}

我已经读了一些关于双下划线如何导致属性名被"损坏"的内容,但是在上面的两种情况下,我都希望相同的名称被损坏。

对象名称前的单下划线和双下划线的含义是什么?

你知道这是怎么回事吗?

损坏的重点正是防止您的第二个案例正常工作。其目的是从外部代码隐藏属性。

名称管理发生在评估class语句期间。在Bar的情况下,__cache属性不定义为类的一部分,而是在事实之后添加到特定对象中。

(实际上,这可能并不完全正确。在评估__new__方法时,可能会出现名称混乱,我不知道。但是无论如何,您的__cache是显式地添加到单个对象中的,而不是由类代码添加的。)

它在编译期间被损坏了。您可以使用dis.dis()函数来查看,只需运行import dis; dis.dis(Foo.__init__)即可查看名称是否已损坏。

很有帮助,谢谢你的解释

从文档中

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 in front of the name, with leading underscores removed, and

a single underscore inserted in front of the class 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.

在定义类之后,您正在分配您的属性

到文档的链接已断开

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值