init期间的python继承函数覆盖

时间:2013-02-28 16:25:55

标签: python inheritance initialization override

不知何故,Father类可以看到Child类的方法。我假设在 init

期间父亲只能使用内部方法

但显然我错了。这是代码:

class Father():
    def __init__(self):
        self.name=self.getName()
        print "from Father ->", self.name

    def getName(self):
        return "father"

class Child(Father):
    def __init__(self):         
        Father.__init__(self)
        self.name=self.getName()
        print "from Child ->", self.name

    def getName(self):
        return "child"

if __name__ == "__main__":
    import sys, pprint

    someone=Child()

输出

from Father -> child
from Child -> child

但我想得到

from Father -> father
from Child -> child

有任何想法如何重写它? Tnx!

1 个答案:

答案 0 :(得分:3)

这是name-mangling的目的:它允许你说:“这个类的属性”:

class Father():
    def __init__(self):
        self.name=self.__getName()
        print "from Father ->", self.name
    def __getName(self):
        return "father"

class Child(Father):
    def __init__(self):         
        Father.__init__(self)
        self.name=self.__getName()
        print "from Child ->", self.name

    def __getName(self):
        return "child"

if __name__ == "__main__":
    import sys, pprint

    someone=Child()

产量

from Father -> father
from Child -> child

有关详细信息,另请参阅this post