1

不知何故,Father 类可以看到 Child 类的方法。我假设在初始化期间只有内部方法可供父亲使用

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

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

任何想法如何重写它?天呐!

4

1 回答 1

3

这是名称修改的目的:它允许您说:“此类的属性”:

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

有关更多信息,另请参阅这篇文章

于 2013-02-28T16:27:56.257 回答