"__"函数的 Python 奇怪覆盖行为

标签 python function private

我发现 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 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.

关于 "__"函数的 Python 奇怪覆盖行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26547421/

相关文章:

java - PowerMock 访问私有(private)成员

python - 写一个生成器还是返回一个生成器?

python - 使用 mongodb (mongoengine) 和 redis 测试 django

R:在循环中定义函数

javascript - JavaScript 中的私有(private)类字段

python - 在 Python 中重新创建 "private"类变量

python - 为什么 "if letter in dict"在 Python 中运行错误?

python - Flask中初始化DB的地方

PHP:未知语法可能是一个没有括号的函数?

javascript - 将函数引用作为回调函数传递