Skip to main content

Understanding Python Class and Super

Python Class:

Class has attributes.
self.fname, self.lname are called attributes.

Class has methods.
Functions inside class are called methods.

Say we have a Person class with attributes fname and lname and method getname which gives fname + lname

Inheritance:
Say we want to create a class Employee, which needs attributes fname, lname and id and methods getname and getid
We can create it from scratch with these attributes and methods.
Or we can inherit Person which already has fname, lname and getname.

Prev: class Person: define __init__(self, fname, lname) and self.fname = fname and self.lname = lname.
Now:  class Employee(Person): define __init__ (self, fname, lname, id) and Person.__init__(self,fname,lname) then you can call self.getname, self.fname, which is from Person class.

Person.__init__(self,fname,lname)  #Avoid this Limits your ability to use multiple inheritance

The __init__ method of our Employee class explicitly invokes the __init__method of the Person class.
We could have used super instead. super().__init__(first, last) is automatically replaced by a call to the superclasses method, in this case __init__.
super().__init__(fname, lname), no need self as well. --> only in python 3
which is same as
super(Employee, self).__init__(fname, lname) --> in python 2 mandatory, in python 3 also it works

https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods/27134600#27134600
https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods

Note that the syntax changed in Python 3.0: you can just say super().__init__() instead of super(Employee, self).__init__()

https://stackoverflow.com/a/55583282/4021879