如何调用继承类的重载函数,而不是在Python中重载父类的函数?

时间:2017-06-13 17:05:15

标签: python inheritance polymorphism

我有两个类似的类SonDaughter,它们具有相同的成员函数ChildWrites但具有不同的实现(多态)。但是这个函数从Write类中的另一个函数Parent调用。

class Parent:

  def __init__(self):
    self.__pathToPocket = "Pocket.txt"                                                          
    print 'What do you want from me, Kid!?'

  def Write(self):
    try:
      f = open(self.__pathToPocket, 'w')
      ChildWrites(self, self.__pathToPocket) 

    except IOError:
      print "Child is too weak to open file. Shame!" 

    finally:
      f.close()

  def ChildWrites(self, pathToPocket):
    raise NotImplementedError("Which of you ask for something again?")


class Son(Parent):

  def __init__(self):
    Parent.__init__(self)
    print('I am your son and ')

  def ChildWrites(self, target):
    target.write('I want money!')


class Daughter(Parent):

  def __init__(self):
    Parent.__init__(self)
    print('I am your daughter and ')

  def ChildWrites(self, target):
    target.write('I want more money!')


Michael = Son()
Michael.Write()
Anna = Daughter()
Anna.Write()

当我运行此代码时,我收到错误:

What do you want from me, Kid!?
I am your son and 
Traceback (most recent call last):
File "./test2.py", line 46, in <module>
Michael.Write()
File "./test2.py", line 13, in Write
ChildWrites(self, self.__pathToPocket) 
NameError: global name 'ChildWrites' is not defined

如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

ChildWrites仍然是一种方法,必须通过在self.前添加前缀,而不是通过传递self作为参数来调用:

self.ChildWrites(self.__pathToPocket)