Académique Documents
Professionnel Documents
Culture Documents
Class Inheritance
Instead of starting from a scratch, you can create a class by deriving it
from a preexisting class by listing the parent class in parentheses after
the new class name.
The child class inherits the attributes of its parent class, and you can use
those attributes as if they were defined in the child class. A child class
can also override data members and methods from the parent.
Derived classes are declared much like their parent class; however, a list
of base classes to inherit from is given after the class name.
Syntax:
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20-… 1/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
In [1]:
class Parent:
def __init__(self):
print("Calling parent constructor")
def parentMethod(self):
print('Calling parent method')
def getAttr(self):
print("Parent attribute :", Parent.parentAttr)
In [2]:
def __init__(self):
print("Calling child constructor")
def childMethod(self):
print('Calling child method')
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20-… 2/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
In [3]:
In [4]:
Multiple Inheritance
In a similar way, you can drive a class from multiple parent classes as
follows −
issubclass() or isinstance() functions can be used to check a
relationships of two classes and instances.
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20-… 3/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
The issubclass(sub, sup) is a boolean function which returns
True, if the given subclass sub is indeed a subclass of the superclass
sup.
The isinstance(obj, Class) is a boolean function which returns
True, if obj is an instance of class Class or is an instance of a subclass
of Class
In [5]:
class Father:
fatherAttr = 1
attr = 9
def __init__(self):
print("Calling father constructor")
def fatherMethod(self):
print('Calling father method')
def getAttr(self):
print("Father attribute :", Father.fatherAttr)
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20-… 4/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
In [6]:
class Mother:
motherAttr = -1
attr = -9
def __init__(self):
print("Calling mother constructor")
def motherMethod(self):
print('Calling mother method')
def getAttr(self):
print("Mother attribute :", Mother.motherAttr)
In [7]:
def __init__(self):
print("Calling child constructor")
def childMethod(self):
print('Calling child method')
In [8]:
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20-… 5/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
In [9]:
print(c.fatherAttr)
print(c.motherAttr)
1
-1
In [10]:
# When attributes have same names, the attribute from the fir
print(c.attr)
In [11]:
# When methods have same names, the method from the first cla
c.getAttr() # calls father's method
c.setAttr(0) # calls father's method
c.getAttr() # calls father's method
Father attribute : 1
Father attribute : 0
In [12]:
In [13]:
Overriding Methods
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20-… 6/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
Overriding Methods
Parent class methods can be always overridden. One reason for
overriding parent's methods is that the user may want special or different
functionality in the subclass.
In [14]:
def myMethod(self):
print('Calling parent method')
def myMethod(self):
print('Calling child method')
In [15]:
In [16]:
The super() function
Returns a proxy object that delegates method calls to a parent or sibling
class of type. This is useful for accessing inherited methods that have
been overridden in a class.
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20-… 7/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
In Python, super() builtin has two major use cases:
Allows us to avoid using base class explicitly in case of Single
Inheritance
Working with Multiple Inheritance
super() function with single inheritance
In [17]:
class Base():
def __init__(self):
print('Base.__init__(self) called')
In [18]:
u = UnSuperChild()
UnSuperChild.__init__(self) called
Base.__init__(self) called
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20-… 8/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
In [19]:
s = SuperChild()
SuperChild.__init__(self) called
Base.__init__(self) called
super() function with multiple inheritance
In [20]:
class A:
def __init__(self):
print("A")
class B(A):
def __init__(self):
print("B")
super().__init__()
class C(A):
def __init__(self):
print("C")
super().__init__()
In [21]:
d = D()
D
B
C
A
Method Resolution Order (MRO)
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20-… 9/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
Method Resolution Order (MRO)
It's the order in which method should be inherited in the presence of
multiple inheritance.
ClassName.__mro__ is the tuple consisting of: the class, its base,
its base's base, and so on up to object.
In [22]:
D.__mro__
Out[22]:
No Method Overloading
Python does NOT traditional method overloading.
However, there are ways to simulate method overloading in python:
1. upack operator * can be used for implementing variable length
arguments to a method.
2. default value of the arguments can set to None.
Polymorphism
Polymorphism is an important feature of class definition in Python that is
utilized when you have commonly named methods across classes or
subclasses. This allows functions to use objects of any of these
polymorphic classes without needing to be aware of distinctions across
the classes.
Polymorphism can be carried out through inheritance, with subclasses
making use of base class methods or overriding them.
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… 10/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
In [23]:
class Tiger(object):
def sound(self):
print("Tiger Roars")
class Dog(object):
def sound(self):
print("Dog Barks")
In [24]:
t = Tiger()
d = Dog()
In [25]:
def makeSound(animal):
animal.sound()
In [26]:
makeSound(t)
makeSound(d)
Tiger Roars
Dog Barks
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… 11/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
In [27]:
class Vehicle(ABC):
@abstractmethod
def drive(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Vehicle):
def drive(self):
return 'Car driving!'
def stop(self):
return 'Car braking!'
class Truck(Vehicle):
def drive(self):
return 'Truck driving!'
def stop(self):
return 'Truck braking!'
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… 12/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
In [28]:
Operator Overloading in Python
Suppose you have created a Vector class to represent twodimensional
vectors. What happens when you use the plus operator to add them?
Most likely Python will yell at you.
__init__(self [, args...]): Constructor (with any optional
arguments)
__del__(self): Destructor, deletes an object
__repr__(self): Evaluatable string representation
__str__(self): Printable string representation str()
__add__(self, other): Addition +
__mul__(self, other): Multiplication *
__sub__(self, other): Subtraction -
__mod__(self, other): Remainder %
__truediv__(self, other): Division /
__lt__(self, other): Less than <
__le__(self, other): Less than or equal to <=
__eq__(self, other): Equal to ==
__ne__(self, other): Not equal to !=
__gt__(self, other): Greater than >
__ge__(self, other): Greater than or equal to >=
__getitem__(self, index): Index operator [index]
__contains__(self, value): Check membership in
__len__(self): The number of elements len()
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… 13/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
In [29]:
class Circle:
def getRadius(self):
return self.__radius
def __str__(self):
return "Circle with radius " + str(self.__radius
In [30]:
c1 = Circle(4)
c2 = Circle(5)
In [31]:
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… 14/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
In [32]:
True
In [33]:
True
In [34]:
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… 15/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
# -----------------------------------------------------------
# OUTPUT:
# Name: FatherName
# Surname: FatherSurname
# Father's Name: FatherName FatherSurname
# -----------------------------------------------------------
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… 17/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
# -----------------------------------------------------------
# -----------------------------------------------------------
# OUTPUT:
# Name: MotherName
# Surname: MotherSurname
# Mother's Name: MotherName MotherSurname
# ---------------------------------------------------
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… --------
18/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
# -----------------------------------------------------------
# -----------------------------------------------------------
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… 19/20
23/02/2018 Module 01 Python Basics - 14 Inheritance
# OUTPUT:
# Name: FatherName
# Surname: FatherSurname
# Name: MotherName
# Surname: MotherSurname
# Name: ChildName
# Child's Name: FatherSurname Child FatherName MotherName
http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… 20/20