0% found this document useful (0 votes)
11 views

Lec 07 - OOP

Uploaded by

Abc
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)
11 views

Lec 07 - OOP

Uploaded by

Abc
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/ 17

Chapter 7

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

Class and Object


 An object consists of a bundle of related state (attributes) and
behavior (methods) that defined from the class.

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

 All members in a Python class are public by default.


 When a Python class is created, it automatically creates
a default no-argument constructor for it.
6

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.

def set_brand(self, brd): • To reference instances (or objects) of the


self.brand = brd # instance attribute class, self will always be the first
parameter, but it need not be the only one.
def get_data(self):
print("This is {} {}".format(self.colour, self.brand)) • toyota is an object / instance of class Car.
• dot operator is used to reference an
def main(): main function attribute of the object.
toyota = Car('silver')
toyota.set_brand('Vios') If the module is run directly,
toyota.get_data() execute the main function
print("The car is made on {} year".format(Car.year)) ( if the module is imported,
don’t run the main function.)
if __name__ == "__main__":
main() 8

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.

Defining a method Calling a method


(inside class definition)

def set_brand(self, brd): >>> toyota.set_brand('Vios')


self.brand = brd
10

5
Class
Instantiating Objects
 There is no "new" keyword as in C++ or Java.
 Syntax:
objectName = className()
 i.e. toyota = Car('silver')

 To access attribute and method:


objectName.attributeName toyota.year
objectName.methodName() toyota.set_brand('Vios')
toyota.get_data()
11

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)

print("obj1 - class attribute:", obj1.classAtr)


print("obj1 - instance attribute:", obj1.insVar ,"\n")
print("obj2 - class attribute:", obj2.classAtr)
print("obj2 - instance attribute:", obj2.insVar, "\n")

classA.classAtr = "The class attribute is changed."


print("obj1 - class attribute:", obj1.classAtr)
print("obj1 - instance attribute:", obj1.insVar ,"\n")
print("obj2 - class attribute:", obj2.classAtr)
print("obj2 - instance attribute:", obj2.insVar, "\n")

if __name__ == "__main__":
main()
14

7
class Car: Class Example 4
count = 0

def __init__(self, brd, prc):


self.brand = brd
self.price = prc
Car.count += 1

def displayCount(self):
print ("Total Car: “, Car.count)

def displayData(self):
print ("Car:", self.brand, ", price:", self.price)

car1 = Car('Vios', 88000)


car2 = Car('Honda', 75000)
car3 = Car('Proton', 60000)
car1.displayData()
car2.displayData()
car3.displayData()
car3.displayCount()
15

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

Class ChildClassName(ParentClassName1, ParentClassName2):


# body of the class
21

Multiple Inheritance Example


# base class 1
class GroundVehicle():
def drive(self):
print("Drive me on the road!")

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

class C(A, B):


def __init__(self):
A.__init__(self)
B.__init__(self)
def getName(self):
• Hence, the name of C become 'FIST'.
return self.name

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.

Getter and Setter methods


 To access and change the private attributes, getter and setter
methods should be used.

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)

ppl = Teacher('John', 32)


ppl.show()

print('Access the private attribute:')


print(ppl.name)
print(ppl.__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))

ppl = Teacher('John', 32)


ppl.show()

print('Access the private method:')


ppl.__work()

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)

def setAge(self, age):


self.__age = age

ppl = Teacher('John', 32)


ppl.show()

ppl.setAge(26) # use setter


ppl.getAge() # use getter 34

17

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy