Lec 07 - OOP
Lec 07 - OOP
Object-Oriented
Programming
Object-Oriented Programming
Class and Object Inheritance
Class Definition Subclassing
Override a Method
Class Examples Add a Method
Class Super() Function
Documentation String Multiple Inheritance
Constructor Method Resolution Order (MRO)
magic keyword "self"
Instantiating Objects Polymorphism
Two types of Attribute Encapsulation
__name__ method
2
1
Class and Object
A class is a blueprint from which individual objects are created.
https://www.listendata.com/2019/08/pyth
on-object-oriented-programming.html 3
https://www.listendata.com/2019/08/pyth
on-object-oriented-programming.html 4
2
Class Definition
A class is a blueprint from which objects are created.
Class can has attributes (properties) and functions.
The functions are indented under a class, they are called
methods.
Classes are defined by the class keyword, followed by the
className and a colon.
class Car:
Empty class - does not have any attributes or methods.
pass
Class Example
Some properties and methods are added to the class.
class Car:
year = 2022 # class attribute
def display(self):
print("The car is made on {} year".format(self.year))
3
Class Example
The constructor can be invoked by creating the instance
/object of the class.
car1 = Car()
print(type(car1))
car1.display()
Output:
<class '__main__.Car'>
The car is made on 2022 year
7
# file car1.py
class Car:
"""A simple class for car""" documentation string
Class Example 2
year = 2021 # class attribute
• The argument to these functions is the
def __init__(self, clr): word self, which is a reference to objects
self.colour = clr # instance attribute that are made based on this class.
4
Class
Documentation String:
A docstring is a string literal that occurs as the first statement
in a module, function, class, or method definition.
The docstring can be accessed using className.__doc__
i.e. Car.__doc__
Constructor:
__init__ is known as a constructor in object oriented concepts.
This method is called when an object is created from the class
and it allows the class to initialize the attributes of a class.
9
Class
Magic keyword "self"
It represents the instance (object) of the class.
It is similar to the keyword "this" in C++ or Java.
It binds the attributes with the given arguments.
It is used to access the methods and attributes of a class.
5
Class
Instantiating Objects
There is no "new" keyword as in C++ or Java.
Syntax:
objectName = className()
i.e. toyota = Car('silver')
Class
Two types of Attribute
Instance Attribute Class Attribute
It is owned by a particular instance of a class. It is owned by the class as a whole.
Each instance has its own value for it. All class instances share the same value for it.
(It is called "static" variables in Java or C++)
It is created and initialized by an __init__() It is defined within a class definition and outside
method. Inside the class, instance attribute is of any method.
referred using self.
class Car: class Car:
year = 2022 # class attribute
def __init__(self, clr):
self.colour = clr # instance attribute
12
6
Class
__name__
When Python runs the "source file" in the current module, it
sets the variable (__name__) to have a value ("__main__").
The if statement ensures, the main function is executed only
as a direct run, not by imported as a module.
if __name__ == "__main__":
main()
13
class classA:
classAtr = "This is a class attribute."
Class Example 3
def __init__(self, num):
self.insVar = num
def main():
obj1 = classA(5)
obj2 = classA(6)
if __name__ == "__main__":
main()
14
7
class Car: Class Example 4
count = 0
def displayCount(self):
print ("Total Car: “, Car.count)
def displayData(self):
print ("Car:", self.brand, ", price:", self.price)
Inheritance
Inheritance is the process of creating a new class from an
existing class.
A class created through inheritance (child class) can use all
the features (attributes and methods) from the parent class.
In the child class:
Extra features can be added
Existing features from the parent class can be overridden.
Inheritance Syntax:
class childClassName(parentClassName):
#body of the child class
16
8
Inheritance
class Vehicle():
"""This is parent class""" Subclassing:
def label(self):
print("This is a Vehicle!") • Car class (child class) inherits the attributes and
methods from the Vehicle class (parent class).
class Car(Vehicle):
"""This is child class""" • "pass" keyword is used when programmer does
pass not want to add any other attributes or methods
to the class.
v1 = Vehicle()
v2 = Car()
v1.label()
v2.label()
17
Inheritance
class Vehicle():
"""This is parent class""" Override a Method(Polymorphism):
def label(self):
print("This is a Vehicle!") • The label() method is added in the Car class.
• When the label() method is called, the Car
class Car(Vehicle):
version of the method is called.
"""This is child class"""
def label(self):
print("This is a Car!") • This is because when a method is added in the
child class with the same name as the parent
v1 = Vehicle() class, it gets overridden.
v2 = Car()
v1.label()
v2.label()
18
9
Inheritance
class Vehicle(): Add a Method:
"""This is parent class"""
def label(self): • The child class can add a method that
print("This is a Vehicle!") was not present in its parent class.
class Car(Vehicle):
"""This is child class"""
• A Car object can react to a setSpeed()
def label(self): method call, but a Vehicle object cannot.
print("This is a Car!")
def setSpeed(self, speed):
print("Now traveling at", speed,"miles per hour")
v1 = Vehicle()
v2 = Car()
v2.setSpeed(25)
v1.setSpeed(25)
19
Inheritance
class Vehicle(): super() Function
"""This is parent class"""
def __init__(self, color):
self.color = color • When programmer override a method, he/she
def label(self): sometimes want to reuse the method of the
print("This is a", self.color, "Vehicle") parent class and add some new stuff.
• super() function is used in the child class to
class Car(Vehicle):
"""This is child class""" access to the attributes and methods of a
def __init__(self, color, style): parent class.
super().__init__(color)
self.style = style
• The __init__() call in the Vehicle class has only
def label(self):
print("This is a", self.color, self.style) "color" parameter while the Car class has an
additional "style" parameter.
v1 = Vehicle('yellow') • The super() invokes the parent class’s
v2 = Car('grey', 'Mini Cooper') __init__() method. Hence, both the color and
v1.label()
v2.label() style attributes can be accessed. 20
10
Multiple Inheritance
Python supports multiple inheritance, where a child class can
inherit from multiple parent classes.
In multiple inheritance, the characteristics of all the parent
classes are inherited into the child class.
Class ParentClassName1:
# body of the class
Class ParentClassName2:
# body of the class
# base class 2
class FlyingVehicle():
def fly(self):
print("Fly me to the sky!")
# subclass
class FlyingCar(GroundVehicle, FlyingVehicle):
pass
v = FlyingCar()
v.drive()
v.fly()
22
Picture source: https://www.learnbyexample.org/python-inheritance/
11
Multiple Inheritance
Method Resolution Order (MRO)
It is the order in which methods of parent class should be inherited
in the presence of multiple inheritance.
class A:
First, it is searched in the current class.
pass If not found, the search moves to parent classes in
class B: depth-first, left-right fashion without searching the
pass same class twice.
class C(A, B): In the example, the search order: C, A, B, Object.
pass
This order is called linearization of class C, and the set
test = C() of rules applied are called Method Resolution Order.
23
Multiple Inheritance
class A:
def __init__(self): • When create instance C1, constructor of C calls the
self.name = 'MMU' constructor of A.
• The value of name in C is assigned as 'MMU' (value of
class B: name in A).
def __init__(self): • When the constructor of B is called, the value of name
self.name = 'FIST' in C is overwritten by the value of name in B due to:
C1 = C()
print(C1.getName())
24
12
Multiple Inheritance
• MRO works in a depth first left to right way.
class A:
• super() in the __init__ method indicates the class that is in
def __init__(self):
self.name = 'MMU' the next hierarchy.
• First, the super() of C indicates A.
class B: • Then, the super() of C go to B.
def __init__(self): • Once the constructor of A is called and attribute 'name' is
self.name = 'FIST' accessed, it does not access the attribute 'name' in B.
• The order in which constructors are called is: C -> A -> B
class C(A, B):
def __init__(self): B
A
super().__init__()
def getName(self):
return self.name
C
C1 = C() Object class is a parent
print(C1.getName()) class for all classes
25
Multiple Inheritance
class A: • Python looks for a method first in class C.
def process(self): • Then it goes to A and then to B.
print('doing A process()') • It goes to first super class given in the list then second super
class, from left to right order.
class B:
• Once process() of A is called, it does not access process() in B.
def process(self):
print('doing B process()') • The order in which constructors are called is:
C -> A -> B
class C(A, B):
pass
obj = C() A B
obj.process()
C.__mro__
C
26
13
Multiple Inheritance
class A: • MRO is : D -> B -> A -> C -> A
def process(self): • If the same class appear in the MRO, the earlier appearances of this
print('doing A process()') class will be remove from the method resolution order.
• On getting the second A from the C, Python will ignore the previous A.
class B(A):
def process(self):
• Once process() of B is called, it does not access process() in A.
print('doing B process()') • MRO in this case is D -> B -> C -> A
A
class C(A):
def process(self):
print('doing C process()')
B C
class D(B, C):
pass
obj = D() D
obj.process()
D.__mro__
27
Polymorphism
Polymorphism means the ability to take various forms.
Method Overriding – it enable programmer to define methods
in the child class that have the same name as the method in
the parent class.
Method Overloading – it does not supported by Python
If a class has multiple methods with the same name, the
method defined in the last will override the earlier method.
28
14
class Faculty:
def greeting(self):
print("Welcome to FIST!")
def brief(self):
Polymorphism Example
print("It is located in Melaka campus.")
class ST(Faculty):
def brief(self):
print("Security Technology.")
class DCN(Faculty):
def brief(self):
print("Data Communications and Networking.")
obj1 = Faculty()
obj2 = ST()
obj3 = DCN()
obj1.greeting()
obj1.brief()
obj2.greeting()
obj2.brief()
obj3.greeting()
obj3.brief()
29
Encapsulation
Encapsulation wrap up data and methods into a single
component and restrict the access to some of the object's
components.
Python provides access to all the attributes and methods
globally.
Python does not have the private keyword (unlike C++ or
Java), but encapsulation can be done.
30
15
Encapsulation
Use Double Underscores
The class members (attributes and methods) can be made to
private by prefixing them with double underscores.
31
Encapsulation Example 1
class Teacher:
def __init__(self, name, age=0):
self.name = name
Try to access private attribute
self.__age = age
def show(self):
print(self.name)
print(self.__age)
32
16
Encapsulation Example 2
class Teacher:
def __init__(self, name, age=0):
self.name = name
self.__age = age Try to access private method
def show(self):
print(self.name)
print(self.__age)
def __work(self):
print("{} works at MMU.".format(self.name))
33
Encapsulation Example 3
class Teacher:
def __init__(self, name, age=0):
self.name = name
self.__age = age Use Getter and Setter methods
def show(self):
print(self.name)
print(self.__age)
def getAge(self):
print(self.__age)
17