【发布时间】:2012-12-14 14:18:40
【问题描述】:
可能重复:
What is the benefit of private name mangling in Python?
我在玩python的时候发现class或者instance变量名如果以2个下划线开头,会被重命名为前面加'_'。
例如
class Test(object):
__attribute = "dunderscored"
def __init__(self, value=0):
self.__instance_attribute = value
test_instance = Test()
那么这两个变量都会被重命名为
test_instance._Test__attribute 和 test_instance._Test__instance_attribute
为什么会有这样的行为/功能?有什么需要,或者有什么特殊用途吗?
我可以想到一个用例,当不同的类有一些具有通用名称的属性时,例如。 value、id、member 是共同的,但对于某些函数/方法,我们只期望/假设这些类中的一个。在这种情况下,有可能没有进行类型检查,当另一个类实例(可能是错误的)传递给它时,可能会导致错误和/或不良行为。
但除了这个用例之外,我看不到这种特殊行为的任何好处。这种行为看起来像是一个功能,非常基本的功能,我觉得我在这里遗漏了一些东西。如果它是一个功能,它有什么用?有什么典型用例吗?
【问题讨论】:
标签: python attributes naming instance-variables class-variables