我发现 Python 中覆盖“__”函数的“奇怪”行为
class A(object):
def foo1(self):
print "foo1 A"
self.test1()
def foo2(self):
print "foo2 A"
self.__test2()
def test1(self):
print "test1 A"
def __test2(self):
print "test2 A"
class B(A):
def test1(self):
print "test1 B"
def __test2(self):
print "test2 B"
ia = A()
ib = B()
ib.foo1()
ib.foo2()
给出结果:
foo1 A
test1 B
foo2 A
test2 A
代替:
foo1 A
test1 B
foo2 A
test2 B
这是 Python "__"函数的正常行为吗?
最佳答案
您看到的行为是在类属性或方法中使用前导双下划线名称的陈述的意图。
以双下划线开头的名称是“损坏的”;为类的名称添加前缀,明确地防止与子类的名称冲突。
参见 Reserved classes of identifiers在引用文档中:
__*
Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes.
(强调我的)
另见 Identifiers section表达式文档:
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 namedHam
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.
关于 "__"函数的 Python 奇怪覆盖行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26547421/