Python Programming Inheritance
Python Programming Inheritance
- Access modifiers
- It is straight forward in c++ , Java - done using the keywords as public, protected,
private
- There is no direct way or keyword available in python for this purpose, yet its
possible using the convention methods.
- Public
- All member variables and methods are public by default.
- Can access class attributes and modify their values outside
class Employee:
def __init__(self, name, sal):
self.name = name
self.salary = sal
e1 = Employee("Aman", 10000)
print("Before Salary ", e1.salary)
e1.salary = 20000
print("After Salary ", e1.salary)
- Protected
- Standard meaning of protected is, class attributes are accessible within
class and its subclasses
- Prefixing single underscore ” _ ” to instance variables is a way of telling
that these are protected and not for accessing outside the class
- Although they can be modified outside as in the below examples shown
(Hence, the responsible programmer would refrain from accessing and
modifying instance variables prefixed with _ from outside its class)
class Employee:
def __init__(self, name, sal):
self._name = name
self._salary = sal
e1 = Employee("Aman", 10000)
print("Before Salary ", e1._salary)
e1._salary = 30000
print("After Salary ", e1._salary)
23
- Private
- Cant be accessed out side the class
class Employee:
def __init__(self, name, sal):
self.__name = name
self.__salary = sal
e1 = Employee("Aman", 10000)
print("Before Salary ", e1.__salary)
- vars() returns dictionary of attributes and their values. It can be applied to class
and objects. When used with objects, returns class attributes and recursively
attributes of classes base class.
- dir() returns list of attributes. It can be applied to class and objects as well. When
used with objects, returns a list of objects attributes and objects class attributes
abd recursively attributes of its classes base class.
24
Python Intricacies:
- Below is an example of calling a class method from another class. Observe the
program and its output-
class Employee:
def __init__(self, n='',a=0, s=0): #instance method
self.__name = n
self.__age = a
self.__salary = s
class Department:
def __init__(self, t, n): #instance method
self.__title = t
self.__id = n
25
Output of above code is below-
Static Method
class Mathematics:
class Dates:
def __init__(self, date):
self.date = date
def getDate(self):
return self.date
26
@staticmethod
def toDashDate(date):
return date.replace("/", "-")
date = Dates("15-12-2016")
dateFromDB = "15/12/2016"
dateWithDash = Dates.toDashDate(dateFromDB)
if(date.getDate() == dateWithDash):
print("Equal")
else:
print("Unequal")
Operator Overloading-
27
Operator Special function Operator Special function
// __floordiv__(self, other)
class Point:
def __init__(self, x=0,y=0):
self.__x = x
self.__y = y
def display_points(self):
print("Points are: ", self.__x, self.__y)
p1 = Point(2,3)
p1.display_points()
p2 = Point(5,5)
p2.display_points()
Points are: 2 3
Points are: 5 5
28
Traceback (most recent call last):
File "/Users/mspangtey/Downloads/DSEU 2022/Odd Sem Python/Python
Programs/operator_overloading.py", line 19, in <module>
print("Combining points are: ", p1 + p2)
TypeError: unsupported operand type(s) for +: 'Point' and 'Point'
Points are: 2 3
Points are: 5 5
Combining points are: (7, 8)
Code Reuse-
Example:
class Department:
def __init__(self,n='',id=0):
self.__name = n
self.__id = id
def display_department(self):
print("Department id is {} and Name is {}".format(self.__id,
self.__name))
class Employee:
def __init__(self, n='', eid= 0):
self.__name = n
self.__eid = eid
self.d_obj = Department('ECE', 28)
def display_employee(self):
print("Employee Name is {}, id is {}".format(self.__name, self.__eid))
29
self.d_obj.display_department()
# print("Employee Name is {}, id is {}, Department is {} and
department id is {}".format(self.__name, self.__eid,
self.d_obj._Department__name, self.d_obj._Department__id))
e1 = Employee("Aman", 101)
e1.display_employee()
- Inheritance
- Used when two classes have a ‘like a’ relationship
- Derived Class can inherit features of Base Class
- Base class is also known as super-class or parent class
- Derived class is also known as subclass or child class
- Derived class object contains all base class data
- Derived class members can access base class members but vice
versa is not true.
- Convention for accessing variables
- var: access anywhere
- _var: access within class and derived class
- __var: access only within class
- Violating the conventions do not throw an error, for for good
practice it should follow the convention
- Accessing __var outside the class is not straight forward like
objectName.__var. This will give error. This is because variable
name gets mangled. So to access such variables the variable is
renames as _ClassName__var. Here ClassName is the class which
contains __var.
Example 1:
class Bird:
def speak(self):
30
print("Inside Bird: Speak")
class Sparrow(Bird):
def sing(self):
print("Inside sparrow: sing")
s1 = Sparrow()
s1.sing()
s1.speak()
Example 2:
class Polygon:
def __init__(self, n):
self.noOfSides = n
sides = [0 for i in range(self.noOfSides)]
def inputSides(self):
self.sides = [float(input("Enter side "+ str(i+1) + " : ")) for
i in range(self.noOfSides)]
def displaySides(self):
for i in range(self.noOfSides):
print("Side ",i+1, " is",self.sides[i])
31
class Triangle(Polygon):
def __init__(self):
super().__init__(3)
# Polygon.__init__(self, 3)
def findArea(self):
a, b, c = self.sides
s = (a+b+c)/2 # s is semiperimeter
area =(s*(s-a)*(s-b)*(s-c))**.5
print("Area of Triangle is %0.2f" %area)
t1 = Triangle()
t1.inputSides()
t1.displaySides()
t1.findArea()
Enter side 1 : 20
Enter side 2 : 30
Enter side 3 : 40
Side 1 is 20.0
Side 2 is 30.0
Side 3 is 40.0
Area of Triangle is 290.47
32
Types of Inheritance-
- issubclass(sub, sup)
- Returns True is sub is derived from sub else returns False
- isinstance(obj, Class)
- Returns True if obj is an object or instance of Class else returns False
print(isinstance(t1, Triangle))
print(isinstance(t1, Polygon))
print(issubclass(Triangle, Polygon))
print(issubclass(Triangle, Polygon))
True
True
True
33
True
Example Below:
class Base:
def display(self):
print("Inside Base")
class Derived1(Base):
def display(Self):
print("Inside Derived 1")
super().display()
class Derived2(Base):
def display(self):
print("Inside Derived2")
super().display()
34
Abstract Class:
class Student(ABC):
@property
def full_name(self):
return f"{self.first_name} {self.lastname}"
@abstractmethod
def getScore(self):
pass
35
class FullTime(Student):
def __init__(self,fn, ln, score):
super().__init__(fn, ln)
self.score = score
def getScore(self):
return self.score
class PartTime(Student):
def __init__(self,fn, ln, credit, hrs):
super().__init__(fn, ln)
self.credit = credit
self.hrs = hrs
def getScore(self):
return self.credit * self.hrs
class ScoreBoard:
def __init__(self):
self.student_list = []
def display_students(self):
for i in self.student_list:
print(f"{i.full_name} \t {i.getScore()}")
sb.display_students()
36