Vous êtes sur la page 1sur 19

23/02/2018 Module 01 Python Basics - 14 Inheritance

Class Inheritance
Instead of starting from a scratch, you can create a class by deriving it
from a pre­existing 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:

class SubClassName(ParentClass1[, ParentClass2,


...]):
"""Optional class documentation string"""
class_suite

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:

# define parent class


parentAttr = 100

def __init__(self):
print("Calling parent constructor")

def parentMethod(self):
print('Calling parent method')

def setAttr(self, attr):


Parent.parentAttr = attr

def getAttr(self):
print("Parent attribute :", Parent.parentAttr)

In [2]:

class Child(Parent): # define child class

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]:

c = Child() # instance of child


c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.getAttr() # again call parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method

Calling child constructor


Calling child method
Calling parent method
Parent attribute : 100
Parent attribute : 200

In [4]:

p = Parent() # instance of parent


p.getAttr() # again call parent's method

Calling parent constructor


Parent attribute : 200

Multiple Inheritance
In a similar way, you can drive a class from multiple parent classes as
follows −

class A: # define your class A


# .....

class B: # define your calss B


# .....

class C(A, B): # subclass of A and B


# .....

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 setAttr(self, attr):


Father.fatherAttr = attr

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 setAttr(self, attr):


Mother.motherAttr = attr

def getAttr(self):
print("Mother attribute :", Mother.motherAttr)

In [7]:

class Child(Father, Mother): # define child class

def __init__(self):
print("Calling child constructor")

def childMethod(self):
print('Calling child method')

In [8]:

c = Child() # instance of child


c.childMethod() # child calls its method
c.fatherMethod() # calls father's method
c.motherMethod() # calls mother's method

Calling child constructor


Calling child method
Calling father method
Calling mother method

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]:

f = Father() # instance of father


f.getAttr() # again call father's method

Calling father constructor


Father attribute : 0

In [13]:

m = Mother() # instance of mother


m.getAttr() # again call mother's method

Calling mother constructor


Mother attribute : -1

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]:

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')

In [15]:

p = Parent() # instance of parent


p.myMethod() # parent called method

Calling parent method

In [16]:

c = Child() # instance of child


c.myMethod() # child calls overridden method

Calling child method

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() built­in 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')

# Referring the base class by using ClassName


class UnSuperChild(Base):
def __init__(self):
print('UnSuperChild.__init__(self) called')
Base.__init__(self)

# Allows us to refer base class by super().


class SuperChild(Base):
def __init__(self):
print('SuperChild.__init__(self) called')
super().__init__()

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__()

class D(B, C):


def __init__(self):
print("D")
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]:

(__main__.D, __main__.B, __main__.C, __ma


in__.A, object)

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]:

# Duck typing in Python

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]:

# Polymorphism using Abstract Classes

from abc import ABC, abstractmethod

class Vehicle(ABC):

def __init__(self, name):


self.name = name

@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]:

vehicles = [Truck('Tata'), Truck('Mahindra'), Car('Honda'

for vehicle in vehicles:


print(vehicle.name + " " + vehicle.drive())

Tata Truck driving!


Mahindra Truck driving!
Honda Car driving!

Operator Overloading in Python
Suppose you have created a Vector class to represent two­dimensional
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 __init__(self, radius):


self.__radius = radius

def getRadius(self):
return self.__radius

def __add__(self, another_circle):


return Circle( self.__radius + another_circle.__radiu

def __gt__(self, another_circle):


return self.__radius > another_circle.__radius

def __lt__(self, another_circle):


return self.__radius < another_circle.__radius

def __str__(self):
return "Circle with radius " + str(self.__radius

In [30]:

c1 = Circle(4)
c2 = Circle(5)

In [31]:

# Became possible because we have added __add__ method


c3 = c1 + c2
print(c3.getRadius())

http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… 14/20
23/02/2018 Module 01 Python Basics - 14 Inheritance

In [32]:

# Became possible because we have added __gt__ method


print(c3 > c2)

True

In [33]:

# Became possible because we have added __lt__ method


print(c1 < c2)

True

In [34]:

# Became possible because we have added __str__ method


print(c3)

Circle with radius 9

http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… 15/20
23/02/2018 Module 01 Python Basics - 14 Inheritance

"""Write a program to demonstrate multiple inheritance in Pyt

# Define a class "Father"


class Father:
def __init__(self):

# Initialize the class "Father" such that:


# instance variable fatherName = None
self.fatherName = None
# instance variable fatherSurname = None
self.fatherSurname = None

# Define a function "setFatherDetails()" such that


# instance variable fatherName = User Input
# instance variable fatherSurname = User Input
def setFatherDetails(self):
self.fatherName=input("ENTER FATHER'S NAME:-")
self.fatherSurname=input("ENTER FATHER'S SURNAME:-"

# Define a function "display()" such that


# it prints Father's name and surname
def display(self):
print(self.fatherName+" "+self.fatherSurname)

# -----------------------------------------------------------

# Create an object "f" for the class "Father"


f=Father()

# call "setFatherDetails()" using "f" object


f.setFatherDetails()

# call "display()" using "f" object


f.display()

# 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
# -----------------------------------------------------------

# Define a class "Mother"


class Mother:

# Initialize the class "Mother" such that:


def __init__(self):
# instance variable motherName = None
self.motherName = None
# instance variable motherSurname = None
self.motherSurname = None

# Define a function "setMotherDetails()" such that


def setMotherDetails(self):
# instance variable motherName = User Input
self.motherName=input("ENTER MOTHER'S NAME:-")
self.motherSurname=input("ENTER MOTHER'S SURNAME:-"
# instance variable motherSurname = User Input

# Define a function "display()" such that


# it prints Mother's name and surname
def display(self):
print(self.motherName+" "+self.motherSurname)

# -----------------------------------------------------------

# Create an object "m" for the class "Mother"


m=Mother()

# call "setMotherDetails()" using "m" object


m.setMotherDetails()

# call "display()" using "m" object


m.display()

# 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

# -----------------------------------------------------------

# Define a class "Child" such that


# it inherits from both "Father" and "Mother" classes
class Child(Father,Mother):

# Initialize the class "Child" such that:


# it initiates the "Father" class
# it initiates the "Mother" class
# instance variable childName = None
def __init__(self):
self.childName=None

# Define a function "setChildDetails()" such that


# instance variable childName = User Input
def setChildDetails(self):
self.childName=input("ENTER CHILD'S NAME:-")

# Define a function "display()" such that


# it prints Child's name in the following format
# "fatherSurname childName fatherName motherName"
def display(self):
print(self.fatherSurname+" "+self.childName+" "

# -----------------------------------------------------------

# Create an object "c" for the class "Child"


c=Child()

# call "setFatherDetails()" using "c" object


c.setFatherDetails()

# call "setMotherDetails()" using "c" object


c.setMotherDetails()

# call "setChildDetails()" using "c" object


c.setChildDetails()

# call "display()" using "c" object


c.display()

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

ENTER FATHER'S NAME:-ASHISH


ENTER FATHER'S SURNAME:-SHAKYA
ASHISH SHAKYA
ENTER MOTHER'S NAME:-MALLIKA
ENTER MOTHER'S SURNAME:-SHAKYA
MALLIKA SHAKYA
ENTER FATHER'S NAME:-AJAY
ENTER FATHER'S SURNAME:-SANGHVI
ENTER MOTHER'S NAME:-SHALINI
ENTER MOTHER'S SURNAME:-SANGHVI
ENTER CHILD'S NAME:-RUDRA
SANGHVI RUDRA AJAY SHALINI

http://localhost:8888/notebooks/Desktop/Module%2001%20Python%20Basics%20… 20/20

Vous aimerez peut-être aussi