0% found this document useful (0 votes)
36 views71 pages

Chapter 3

The document discusses operator overloading and inheritance in Python. It covers various types of operators in Python like arithmetic, comparison, logical, assignment and bitwise operators. It also explains operator precedence and overloading operators to extend their functionality for different data types. The document then discusses inheritance in Python and different types of inheritance in derived classes.

Uploaded by

Pratik Kanjilal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views71 pages

Chapter 3

The document discusses operator overloading and inheritance in Python. It covers various types of operators in Python like arithmetic, comparison, logical, assignment and bitwise operators. It also explains operator precedence and overloading operators to extend their functionality for different data types. The document then discusses inheritance in Python and different types of inheritance in derived classes.

Uploaded by

Pratik Kanjilal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Chapter 3

Operator Overloading and


Inheritance
Declaration
 These slides are made for UIT, BU students only. I am not
holding any copy write of it as I had collected these study
materials from different books and websites etc. I have not
mentioned those to avoid complexity.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.2


Topics
 Concept of Operator Overloading
 Different types of Operator Overloading
 Concept of Inheritance
 Different types of Inheritance in derived class and
implementation

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.3


Python - Basic Operators
Python language supports following type of operators.
 Arithmetic Operators
 Comparision Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.4


Python Arithmetic Operators

Operator Description Example


+ Addition - Adds values on either side of the a + b will give 30, if
operator a=10 and b=20
- Subtraction - Subtracts right hand operand a - b will give -10
from left hand operand
* Multiplication - Multiplies values on either a * b will give 200
side of the operator
/ Division - Divides left hand operand by b / a will give 2
right hand operand
% Modulus - Divides left hand operand by b % a will give 0
right hand operand and returns remainder
** Exponent - Performs exponential (power) a**b will give 10 to
calculation on operators the power 20
// Floor Division - The division of operands 9//2 is equal to 4 and
where the result is the quotient in which 9.0//2.0 is equal to 4.0
the digits after the decimal point are
removed.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.5


Python Comparison Operators

Operato
Description Example
r
== Checks if the value of two operands are equal or not, if (a == b) is not true.
yes then condition becomes true.
!= Checks if the value of two operands are equal or not, if (a != b) is true.
values are not equal then condition becomes true.
<> Checks if the value of two operands are equal or not, if (a <> b) is true. This is
values are not equal then condition becomes true. similar to != operator.
> Checks if the value of left operand is greater than the (a > b) is not true.
value of right operand, if yes then condition becomes
true.
< Checks if the value of left operand is less than the (a < b) is true.
value of right operand, if yes then condition becomes
true.
>= Checks if the value of left operand is greater than or (a >= b) is not true.
equal to the value of right operand, if yes then
condition becomes true.
<= Checks if the value of left operand is less than or equal (a <= b) is true.
to the value of right operand, if yes then condition
becomes true.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.6


Python Assignment Operators

Operator Description Example


= Simple assignment operator, Assigns values from right c = a + b will
side operands to left side operand assigne value of a +
b into c
+= Add AND assignment operator, It adds right operand to c += a is equivalent
the left operand and assign the result to left operand to c = c + a
-= Subtract AND assignment operator, It subtracts right c -= a is equivalent
operand from the left operand and assign the result to left to c = c - a
operand
*= Multiply AND assignment operator, It multiplies right c *= a is equivalent
operand with the left operand and assign the result to left to c = c * a
operand
/= Divide AND assignment operator, It divides left operand c /= a is equivalent
with the right operand and assign the result to left to c = c / a
operand
%= Modulus AND assignment operator, It takes modulus c %= a is equivalent
using two operands and assign the result to left operand to c = c % a
**= Exponent AND assignment operator, Performs exponential c **= a is
(power) calculation on operators and assign value to the equivalent to c = c
left operand ** a
//= Floor Division and assigns a value, Performs floor division c //= a is equivalent
on operators and assign value to the left operand to c = c // a
9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.7
Python Bitwise Operators

Operat
Description Example
or
& Binary AND Operator copies a bit to the (a & b) will give 12
result if it exists in both operands. which is 0000 1100
| Binary OR Operator copies a bit if it exists (a | b) will give 61
in either operand. which is 0011 1101
^ Binary XOR Operator copies the bit if it is (a ^ b) will give 49
set in one operand but not both. which is 0011 0001
~ Binary Ones Complement Operator is unary (~a ) will give -60
and has the effect of 'flipping' bits. which is 1100 0011
<< Binary Left Shift Operator. The left a << 2 will give 240
operands value is moved left by the which is 1111 0000
number of bits specified by the right
operand.
>> Binary Right Shift Operator. The left a >> 2 will give 15
operands value is moved right by the which is 0000 1111
number of bits specified by the right
operand.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.8


Python Logical Operators

Operat
Description Example
or
and Called Logical AND operator. If both the (a and b) is true.
operands are true then then condition
becomes true.
or Called Logical OR Operator. If any of the two (a or b) is true.
operands are non zero then then condition
becomes true.
not Called Logical NOT Operator. Use to not(a and b) is false.
reverses the logical state of its operand. If a
condition is true then Logical NOT operator
will make false.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.9


Python Membership Operators

In addition to the operators discussed previously, Python has


membership operators, which test for membership in a sequence,
such as strings, lists, or tuples.

Operator Description Example

in Evaluates to true if it finds a variable in the x in y, here in results in a


specified sequence and false otherwise. 1 if x is a member of
sequence y.

not in Evaluates to true if it does not finds a x not in y, here not in


variable in the specified sequence and false results in a 1 if x is a
otherwise. member of sequence y.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.10


Python Operators Precedence

Operator Description
** Exponentiation (raise to the power)
~+- Ccomplement, unary plus and minus (method names for
the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += Assignment operators
*= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators
9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.11
Operator Overloading in Python
Operator Overloading means giving extended meaning beyond
their predefined operational meaning. For example operator + is
used to add two integers as well as join two strings and merge two
lists. It is achievable because „+‟ operator is overloaded by int class
and str class. You might have noticed that the same built-in
operator or function shows different behavior for objects of different
classes, this is called Operator Overloading.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.12


Operator Overloading in Python
# Python program to show use of
# + operator for different purposes

# + adding two int numbers


print(1 + 2)

# concatenate two strings


print(“UIT"+"For")

# Product two numbers


print(3 * 4)

# Repeat the String


print(“UIT"*4)

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.13


Operator Overloading in Python
Output:
3
UIT For
12
UITUITUITUIT

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.14


Operator Overloading in Python
 Consider that we have two objects which are a physical
representation of a class (user-defined data type) and we have
to add two objects with binary „+‟ operator it throws an error,
because compiler don‟t know how to add two objects.
 So we define a method for an operator and that process is
called operator overloading.
 We can overload all existing operators but we can‟t create a
new operator.
 To perform operator overloading, Python provides some special
function or magic function that is automatically invoked when it
is associated with that particular operator.
 For example, when we use + operator, the magic method
__add__ is automatically invoked in which the operation for +
operator is defined.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.15


Operator Overloading in Python
 Changing the behavior of operator is as simple as changing the
behavior of method or function.
 You define methods in your class and operators work according
to that behavior defined in methods.
 When we use + operator, the magic method __add__ is
automatically invoked in which the operation for + operator is
defined.
 There by changing this magic method‟s code, we can give extra
meaning to the + operator.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.16


Operator Overloading in Python
# Python Program illustrate how
# to overload an binary + operator

class A:
def __init__(self, a):
self.a = a

# adding two objects


def __add__(self, o):
return self.a + o.a
ob1 = A(1)
ob2 = A(2)
ob3 = A(“UIT")
ob4 = A("For")

print(ob1 + ob2)
print(ob3 + ob4)
9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.17
Operator Overloading in Python
Output:
3
UITFor

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.18


Operator Overloading in Python
# Python Program to perform addition
# of two complex numbers using binary
# + operator overloading.

class complex:
def __init__(self, a, b):
self.a = a
self.b = b

# adding two objects


def __add__(self, other):
return self.a + other.a, self.b + other.b

Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2
print(Ob3)
9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.19
Operator Overloading in Python
Output:
(3, 5)

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.20


Operator Overloading in Python
# Python program to overload
# a comparison operators

class A:
def __init__(self, a):
self.a = a
def __gt__(self, other):
if(self.a>other.a):
return True
else:
return False
ob1 = A(2)
ob2 = A(3)
if(ob1>ob2):
print("ob1 is greater than ob2")
else:
print("ob2 is greater than ob1")
9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.21
Operator Overloading in Python
Output:
ob2 is greater than ob1

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.22


Operator Overloading in Python
class A:
def __init__(self, a):
self.a = a
def __lt__(self, other):
if(self.a<other.a):
return "ob1 is less than ob2"
else:
return "ob2 is less than ob1"
def __eq__(self, other):
if(self.a == other.a):
return "Both are equal"
else:
return "Not equal"

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.23


Operator Overloading in Python
ob1 = A(2)
ob2 = A(3)
print(ob1 < ob2)

ob3 = A(4)
ob4 = A(4)
print(ob1 == ob2)

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.24


Operator Overloading in Python
Output:
ob1 is less than ob2
Not equal

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.25


Operator Overloading in Python
Binary Operators
+ __add__(self, other)
– __sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
// __floordiv__(self, other)
% __mod__(self, other)
** __pow__(self, other)
>> __rshift__(self, other)
<< __lshift__(self, other)
& __and__(self, other)
| __or__(self, other)
^ __xor__(self, other)

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.26


Operator Overloading in Python
Comparison Operators :

< __lt__(self, other)


> __gt__(self, other)
<= __le__(self, other)
>= __ge__(self, other)
== __eq__(self, other)
!= __ne__(self, other)

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.27


Operator Overloading in Python
Assignment Operators :
-= __isub__(self, other)
+= __iadd__(self, other)
*= __imul__(self, other)
/= __idiv__(self, other)
//= __ifloordiv__(self, other)
%= __imod__(self, other)
**= __ipow__(self, other)
>>= __irshift__(self, other)
<<= __ilshift__(self, other)
&= __iand__(self, other)
|= __ior__(self, other)
^= __ixor__(self, other)

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.28


Operator Overloading in Python
Unary Operators :

– __neg__(self)
+ __pos__(self)
~ __invert__(self)

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.29


Any and All in Python
 Any and All are two built ins provided in python used for
successive Or/And.
 Any: Returns true if any of the items is True. It returns False if
empty or all are false. Any can be thought of as a sequence of
OR operations on the provided iterables. It short circuit the
execution i.e. stop the execution as soon as the result is known.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.30


Any and All in Python
# Since all are false, false is returned
print (any([False, False, False, False]))

# Here the method will short-circuit at the


# second item (True) and will return True.
print (any([False, True, False, False]))

# Here the method will short-circuit at the


# first (True) and will return True.
print (any([True, False, False, False]))

Output:
False
True
True

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.31


Any and All in Python
All: Returns true if all of the items are True (or if the iterable is
empty). All can be thought of as a sequence of AND operations on
the provided iterables. It also short circuit the execution i.e. stop the
execution as soon as the result is known.

# Here all the iterables are True so all


# will return True and the same will be printed
print (all([True, True, True, True]))

# Here the method will short-circuit at the


# first item (False) and will return False.
print (all([False, True, True, False]))

# This statement will return False, as no


# True is found in the iterables
print (all([False, False, False]))
9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.32
Any and All in Python
Output:
True
False
False

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.33


Any and All in Python
# This code explains how can we
# use 'any' function on list
list1 = []
list2 = []

# Index ranges from 1 to 10 to multiply


for i in range(1,11):
list1.append(4*i)

# Index to access the list2 is from 0 to 9


for i in range(0,10):
list2.append(list1[i]%5==0)

print('See whether at least one number is divisible by 5 in list 1=>')


print(any(list2))

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.34


Any and All in Python
Output:
See whether at least one number is divisible by 5 in list 1=>
True

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.35


Any and All in Python
# Illustration of 'all' function in python 3

# Take two lists


list1=[]
list2=[]

# All numbers in list1 are in form: 4*i-3


for i in range(1,21):
list1.append(4*i-3)

# list2 stores info of odd numbers in list1


for i in range(0,20):
list2.append(list1[i]%2==1)

print('See whether all numbers in list1 are odd =>')


print(all(list2))

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.36


Any and All in Python
Output:
See whether all numbers in list1 are odd =>
True

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.37


Any and All in Python
Truth table :-

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.38


Inheritance
 Inheritance is the capability of one class to derive or inherit the
properties from another class.
 Benefits of inheritance are:
 It represents real-world relationships well.
 It provides the reusability of a code. We don‟t have to write the
same code again and again. Also, it allows us to add more features
to a class without modifying it.
 It is transitive in nature, which means that if class B inherits from
another class A, then all the subclasses of B would automatically
inherit from class A.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.39


Inheritance
 Python Inheritance Syntax
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.40


Inheritance
 Creating a Parent Class
class Person(object):
# Constructor
def __init__(self, name, id):
self.name = name
self.id = id
# To check if this person is an employee
def Display(self):
print(self.name, self.id)
# Driver code
emp = Person("Satyam", 102) # An Object of Person
emp.Display()

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.41


Inheritance
 Output:
Satyam 102

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.42


Inheritance
 Creating a Child Class
class Emp(Person):

def Print(self):
print("Emp class called")

Emp_details = Emp("Mayank", 103)

# calling parent class function


Emp_details.Display()

# Calling child class function


Emp_details.Print()

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.43


Inheritance
 Output:
Mayank 103
Emp class called

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.44


Inheritance
 Example of Inheritance in Python
# A Python program to demonstrate inheritance

# Base or Super class. Note object in bracket.


# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"

class Person(object):
# Constructor
def __init__(self, name):
self.name = name

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.45


Inheritance
# To get name
def getName(self):
return self.name
# To check if this person is an employee
def isEmployee(self):
return False

# Inherited or Subclass (Note Person in bracket)


class Employee(Person):

# Here we return true


def isEmployee(self):
return True

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.46


Inheritance
# Driver code
emp = Person(“UIT1") # An Object of Person
print(emp.getName(), emp.isEmployee())

emp = Employee("UIT2") # An Object of Employee


print(emp.getName(), emp.isEmployee())

Output:
UIT1 False
UIT2 True

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.47


Inheritance
 What is object class?
 Like the Java Object class, in Python (from version 3. x), the object
is the root of all classes.
 In Python 3.x, “class Test(object)” and “class Test” are same.
 In Python 2. x, “class Test(object)” creates a class with the object as
a parent (called a new-style class), and “class Test” creates an old-
style class (without an objecting parent).
 Subclassing (Calling constructor of parent class)
 A child class needs to identify which class is its parent class. This
can be done by mentioning the parent class name in the definition of
the child class.
 Eg: class subclass_name (superclass_name):

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.48


Inheritance
# Python code to demonstrate how parent constructors
# are called.

# parent class
class Person(object):

# __init__ is known as the constructor


def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber

def display(self):
print(self.name)
print(self.idnumber)

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.49


Inheritance
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post

# invoking the __init__ of the parent class


Person.__init__(self, name, idnumber)

# creation of an object variable or an instance


a = Employee('Rahul', 886012, 200000, "Intern")

# calling a function of the class Person using its instance


a.display()

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.50


Inheritance
 Output:
Rahul
886012

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.51


Inheritance
 „a‟ is the instance created for the class Person. It invokes the
__init__() of the referred class. You can see „object‟ written in the
declaration of the class Person. In Python, every class inherits
from a built-in basic class called „object‟. The constructor i.e. the
„__init__‟ function of a class is invoked when we create an object
variable or an instance of the class.
 The variables defined within __init__() are called the instance
variables. Hence, „name‟ and „idnumber‟ are the instance
variables of the class Person. Similarly, „salary‟ and „post‟ are the
instance variables of the class Employee. Since the class
Employee inherits from class Person, „name‟ and „idnumber‟ are
also the instance variables of class Employee.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.52


Inheritance
 Python program to demonstrate error if we forget to invoke
__init__() of the parent
 If you forget to invoke the __init__() of the parent class then its instance
variables would not be available to the child class.
 The following code produces an error for the same reason.
class A:
def __init__(self, n='Rahul'):
self.name = n

class B(A):
def __init__(self, roll):
self.roll = roll

object = B(23)
print(object.name)
9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.53
Inheritance
 Output :
Traceback (most recent call last):
File "/home/de4570cca20263ac2c4149f435dba22c.py", line 12, in
print (object.name)
AttributeError: 'B' object has no attribute 'name'

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.54


Different types of Inheritance
 Different types of Inheritance:
 Single inheritance: When a child class inherits from only one
parent class, it is called single inheritance. We saw an example
above.
 Multiple inheritances: When a child class inherits from multiple
parent classes, it is called multiple inheritances. Unlike java, python
shows multiple inheritances.
 Multilevel inheritance: When we have a child and grandchild
relationship.
 Hierarchical inheritance More than one derived class are created
from a single base.
 Hybrid inheritance: This form combines more than one form of
inheritance. Basically, it is a blend of more than one type of
inheritance.

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.55


Different types of Inheritance

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.56


Different types of Inheritance

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.57


Different types of Inheritance

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.58


Different types of Inheritance

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.59


Different types of Inheritance

Hybrid Inheritance

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.60


Multiple Inheritance
# Python example to show the working of multiple
# inheritance

class Base1(object):
def __init__(self):
self.str1 = “UIT1"
print("Base1")

class Base2(object):
def __init__(self):
self.str2 = “UIT2"
print("Base2")

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.61


Multiple Inheritance
class Derived(Base1, Base2):
def __init__(self):

# Calling constructors of Base1


# and Base2 classes
Base1.__init__(self)
Base2.__init__(self)
print("Derived")

def printStrs(self):
print(self.str1, self.str2)

ob = Derived()
ob.printStrs()

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.62


Multiple Inheritance
 Output:
Base1
Base2
Derived
UIT1 UIT2

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.63


Multilevel Inheritance
# A Python program to demonstrate inheritance

# Base or Super class. Note object in bracket.


# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"
class Base(object):
# Constructor
def __init__(self, name):
self.name = name
# To get name
def getName(self):
return self.name

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.64


Multilevel Inheritance
# Inherited or Sub class (Note Person in bracket)
class Child(Base):

# Constructor
def __init__(self, name, age):
Base.__init__(self, name)
self.age = age

# To get name
def getAge(self):
return self.age

# Inherited or Sub class (Note Person in bracket)

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.65


Multilevel Inheritance
class GrandChild(Child):

# Constructor
def __init__(self, name, age, address):
Child.__init__(self, name, age)
self.address = address

# To get address
def getAddress(self):
return self.address

# Driver code
g = GrandChild("Geek1", 23, "Noida")
print(g.getName(), g.getAge(), g.getAddress())

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.66


Multilevel Inheritance
Output:
Geek1 23 Noida

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.67


Inheritance
 Private members of the parent class
 We don‟t always want the instance variables of the parent class
to be inherited by the child class i.e. we can make some of the
instance variables of the parent class private, which won‟t be
available to the child class.
 We can make an instance variable private by adding double
underscores before its name. For example,
# Python program to demonstrate private members
# of the parent class
class C(object):
def __init__(self):
self.c = 21

# d is private instance variable


self.__d = 42
9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.68
Inheritance
class D(C):
def __init__(self):
self.e = 84
C.__init__(self)

object1 = D()

# produces an error as d is private instance variable


print(object1.d)

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.69


Multiple Inheritance
 Output :
File "/home/993bb61c3e76cda5bb67bd9ea05956a1.py", line 16, in
print (object1.d)
AttributeError: type object 'D' has no attribute 'd'

9/8/2023 2:24 PM Dr. Dipankar Dutta, UIT, BU 1.70


End of Chapter 3

Questions?

You might also like