我有两个类似的类Son
和Daughter
,它们具有相同的成员函数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
如何解决这个问题?
答案 0 :(得分:2)
ChildWrites
仍然是一种方法,必须通过在self.
前添加前缀,而不是通过传递self
作为参数来调用:
self.ChildWrites(self.__pathToPocket)