Python Forum
Is any super keyword like java - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Is any super keyword like java (/thread-5005.html)



Is any super keyword like java - rajeev1729 - Sep-14-2017

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



RE: Is any super keyword like java - buran - Sep-14-2017

https://www.blog.pythonlibrary.org/2014/01/21/python-201-what-is-super/


RE: Is any super keyword like java - snippsat - Sep-14-2017

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>