Python双下划线修饰 [英] Python double underscore mangling

查看:99
本文介绍了Python双下划线修饰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种行为让我有些困惑(使用python 3.2):

I am a bit confused by this behavior (using 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}

我已经读过一些有关如何使用双下划线引起属性名称混乱"的信息,但是我希望在上述两种情况下都可以使用相同的名称处理方式.

I've read up a bit on how double-underscores cause attribute names to be "mangled", but I would have expected the same name-mangling in both cases above.

在对象名称之前使用单下划线和双下划线是什么意思?

有什么想法吗?

推荐答案

在对class语句求值期间会发生名称重整.对于Bar__cache属性未定义为类的一部分,而是在事实之后添加到特定对象中.

Name mangling occurs during the evaluation of a class statement. In the case of Bar, the __cache attribute is not defined as part of the class, but rather added to a specific object after the fact.

(实际上,这可能并不完全正确.在评估__new__方法的过程中可能会发生名称重整;我不知道.但是无论如何,您的__cache是显式添加到单个对象中,而不是通过类代码.)

(Actually, that may not be entirely correct. Name mangling may occur during the evaluation of the __new__ method; I do not know. But regardless, your __cache is added explicitly to a single object, not added by the class code.)

这篇关于Python双下划线修饰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆