Wolfgang Wolfgang -4 years ago 101
Python Question

How to call overloaded function of inherited class inside not overloaded function of a parent class in Python?

I have two similar classes

Son
and
Daughter
which have the same member function
ChildWrites
but different realization (polymorphism). But this function calls from another function
Write
inside
Parent
class.

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()


When I run this code I get the error:

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


How to fix this?

Answer Source

ChildWrites is still a method and must be called as such by prefixing it with self., not by passing self as an argument:

self.ChildWrites(self.__pathToPocket)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download