Python Forum

Full Version: Is any super keyword like java
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
how to print "Calling parent method" using Child object.
class Parent:        # define parent class
   def myMethod(self):
      print ('Calling parent method')

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

c = Child()          # instance of child
c.myMethod()         # child calls overridden method
The Super() call has been simpler in Python 3,in link of buran is mention but not shown.
So super(Child, self).my_method() becomes super().my_method().
λ ptpython
>>> class Parent:
...     def my_method(self):
...         print('Calling parent method')
...
... class Child(Parent):
...     def my_method(self):
...         print('Calling child method')
...         super().my_method()

>>> c = Child()
>>> c.my_method()
Calling child method
Calling parent method
You must always call the original implementation.
By calling the original implementation,you get the result you later want to improve.
Super() follow mro that moving up the inheritance tree.
>>> Child.mro()
[<class '__main__.Child'>, <class '__main__.Parent'>, <class 'object'>]
When override have to think if you want to filter the arguments for the original implementation,
before,after or both.
Example pre-filter.
Add some information before calling(original implementation) of time_show method.
λ ptpython
>>> from datetime import datetime
...
... class Show(object):
...     def time_show(self, message):
...         print(message)
...
... class TimeNow(Show):
...     def time_show(self, message):
...         message = f"<{datetime.now()}> <{message}>"
...         super().time_show(message)

>>> t = TimeNow()
>>> t.time_show('Hello world')
<2017-09-14 21:42:45.814203> <Hello world>