2

How can I access a parent method using function over-riding in python? See example below:

class Parent:      
   def myMethod(self):
      print 'Calling parent method'

class Child(Parent):
   def myMethod(self):
      print 'Calling child method'

c = Child()        
c.myMethod()

Is this a proper function overriding solution?

midhun pc
  • 41
  • 6
  • 1
    That depends. _Where_ do you want to call the parent method? – Aran-Fey Apr 16 '18 at 08:45
  • 1
    Possible duplicate of [Call a parent class's method from child class in Python?](https://stackoverflow.com/questions/805066/call-a-parent-classs-method-from-child-class-in-python) –  Apr 16 '18 at 08:45
  • Do you mean "how to access a parent function when that function has been overriden on the child class"? – juanpa.arrivillaga Apr 16 '18 at 08:47

1 Answers1

1

You need to define Parent as a new-style class: Parent(object) and use super(Child, self).myMethod() in Child. Pyfiddle

class Parent(object):      
   def myMethod(self):
      print 'Calling parent method'

class Child(Parent):
   def myMethod(self):
      super(Child, self).myMethod()
      print 'Calling child method'

c = Child()
c.myMethod()
raul.vila
  • 1,984
  • 1
  • 11
  • 24