0% found this document useful (0 votes)
53 views46 pages

Chapter 4 - Object Oriented Programming

python

Uploaded by

Duc Vuong Nguyen
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)
53 views46 pages

Chapter 4 - Object Oriented Programming

python

Uploaded by

Duc Vuong Nguyen
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/ 46

EE3491 – KỸ THUẬT LẬP TRÌNH

PROGRAMMING TECHNIQUES

CHAPTER 4
Object-Oriented Programming
Võ Duy Thành
Department of Automation Engineering
Control Technique and Innovation Lab. for Electric Vehicles
School of Electrical and Electronic Engineering
Hanoi University of Science and Technology
[email protected] | [email protected]
Outline

1. Introduction
2. Class and Abstraction
3. Inheritance
4. Encapsulation and Information Hiding
5. Polymorphism

2
1. Introduction | 1.1. Objects

Vehicle/Car
Electric Vehicle Air conditioner

SUV Cruise Control

Vinfast
Navigating

Grey color

Listen to music
IPM Motor Everything is object!

Battery Driving with steer


5 seats and pedals

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 3


1. Introduction | 1.1. Objects

Vehicle/Car
Electric Vehicle Air conditioner

SUV Cruise Control

Vinfast
Navigating

Grey color

Listen to music
IPM Motor
Battery Driving with steer
5 seats and pedals

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 4


1. Introduction | 1.1. Objects

Vehicle/Car This is an instance of a larger category: Means of Transportation


Type of an object
Electric Vehicle
SUV Vinfast
These present the attributes of the object Vehicle
Grey color Battery Internal data representation
5 seats IPM Motor

Air conditioner
Cruise Control
Listen to music These present how to manipulate the object Vehicle
Navigating
Procedures for interaction with the object
Driving with steer
and pedals

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 5


1. Introduction | 1.1. Objects

• In Object-Oriented Programming Language, everything is an object


• Every object has:
• A type
• An internal data representation (primitive or composite)
• A set of procedures to interact with the object
• From that, we can:
• Create new objects of some types
• Manipulate objects
• Destroy objects
• There are various built-in types in OOP languages:
• For C: bool, char, int, float, double, array…
• For Python: bool, int, float, list, tuple, dictionary…

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 6


1. Introduction | 1.1. Objects

• Example:
• List-type object in Python L = [1, 2, 3, 4]
• Internal representation of object L: Behind the scene

L = 1 → 2 → 3 → 4 →

• Manipulate the object L:


• L[i], L[i:j], + The pointer contains the
• len(), min(), max(), del(L[i]) location of the next element
• L.append(), L.extend(), L.count(), L.index()
• L.insert(), L.pop(), L.remove(), L.reverse(), L.sort()
• Note:
• Internal representation should be private

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 7


1. Introduction | 1.2. Definition

• OOP is a programming paradigm used to structure a program into


simple, reusable pieces of code. OOP relies on classes and objects.
• Advantages of OOP
• Bundle data into packages together with methods that work on them through
well-defined interfaces
• Divide-and-Conquer development
• Easy for implementation and separated tests
• Modularization reduces complexity
• Code reuse
• Scalable from small to larger system
• Effective for solving problem

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 8


1. Introduction | 1.2. Definition

• Four main features of OOP


Object: My Car
1. Data abstraction using class. An object captures
•Attribute:
• An internal representation through data attributes Class: Car •Color = Black
• An interface for interacting with objects •Brand = BMW
•Attribute: •Model = X3
• through methods •Color •Method
• defines behaviors but hides implementation •Brand •repaint()
•Model
2. Encapsulation: also called data-hiding, wrapping •Method
up data under a single unit •repaint() Object: SonsCar
• The mechanism to bind code and data •Attribute:
• Data or variables in a class are hidden from other •Color = Red
•Brand = BMW
classes Encapsulation •Model = 325
•Method
•repaint()
Variables
Class Methods
Data

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 9


1. Introduction | 1.2. Definition

• Four main features of OOP (cont.)


3. Inheritance: a class can inherit (reuse) properties of the higher level classes
Parent Class Parent Class Parent Class Parent Class

Child Class Child Class Child Class 1 Child Class 2 Child Class 3
Single Inheritance Multiple Inheritance Hierarchical Inheritance

Parent Class Parent Class


A

Derived Class 1 B C
Derived Class Derived Class
Derived Class 2
D Hybrid Class
Multi-level Inheritance Derived Class

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 10


1. Introduction | 1.2. Definition

• Four main features of OOP (cont.)


4. Polymorphism:
• The ability of an object to be displayed in more than one form
• The object can share behaviors
• The ability to present the same interface for different underlying forms (data types)
• Two mechanisms of polymorphism:
• Overloading: multiple methods have the same name but different parameters
• Overriding: the sub-class provides its method that is already defined in the super-class

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 11


2. Class and Abstraction | 2.1. Class

• Class in OOP is a user-defined data type.


• Class consists of data members and member functions.
⇒ A class can be seen as a blueprint for an object.
• Creating a class involves
• Defining the class name
• Defining class attributes
Example: Someone wrote code to implement a list class
• Using the class involves
• Creating new instances of object
• Perform operations on the instances
Example: L = [1, 2] and len(L)

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 12


2. Class and Abstraction | 2.2. Implementing the class

• Define a class by the keyword “class”


Class definition Name/Type Class parent

class Class_Name(object):
Indent # define attributes here
Example: class Coordinate(object)

• “object” means that: Coordinate is an object and inherits all


attributes of object
• Coordinate is a sub-class of object
• object is a super-class of Coordinate

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 13


2. Class and Abstraction | 2.2. Implementing the class

What are attributes?


• Data and procedures that belong to the class
• Data attributes
• Data as other object that make up the class
• Example: a coordinate is made up of two numbers
• Methods (procedural attributes)
• Methods as functions that only work with this class
• Provide ways to interact with the object
• Example: you can define a distance between two points (coordinate objects),
but there is no meaning to a distance between two list objects

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 14


2. Class and Abstraction | 2.2. Implementing the class

• Create an instance of the object using a special method called


__init__ to initialize some data attributes
Data initializes a
Coordinate object
class Coordinate(object) :
def __init__(self, x, y) :
self.x = x
Special method to Parameter to refer to
self.y = y
create an instance an instance of the class

Two data attributes for


every Coordinate object

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 15


2. Class and Abstraction | 2.2. Using the class

• Creating an instance of a class Create a new object of


type Coordinate, named c,
then pass in 4, 6 to the __init__
c = Coordinate(4, 6)
b = Coordinate(4, 9)
origin = Coordinate(0, 0)
print(c.x, c.y) Use dot ( . ) to access the attributes
print(b.x, b.y) of the instance c

print(origin.x, origin.y)

• Data attributes of an instance are called instance variable

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 16


2. Class and Abstraction | 2.2. Working with Method

• What is a method?
• Procedural attribute. Similar to the function concept but method works only
with the belonging class
• In Python (as an example), the object is passed as the first argument
• Conventionally, the self is used as the name of the first argument of all method
• The “.” operator is used to access any attribute
• A data attribute of an object
• A method of an object
• Without self and dot, a method is just like a normal function (take input
parameters, do something, and return the result)

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 17


2. Class and Abstraction | 2.2. Working with Method

• Example: Defining a method for the Coordinate class


class Coordinate(object) : Use self to refer to any instance
def __init__(self, x, y) :
self.x = x Another parameter to the method
self.y = y Use dot to access data
def distance(self, other) :
x_diff_sq = (self.x - other.x)**2
y_diff_sq = (self.y - other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
→ self and dot make the difference between a method of a class and
normal function

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 18


2. Class and Abstraction | 2.2. Working with Method

• Use of method

Conventional way Equivalent way


c = Coordinate(3,4) c = Coordinate(3,4)
zero = Coordinate(0,0) zero = Coordinate(0,0)
print(c.distance(zero)) print(Coordinate.distance(c, zero))

Object to self is not included Name of method


call method (it is implied to be c)
Input parameters
Name of method Name of class
self (c) is included

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 19


2. Class and Abstraction | 2.3. Special Methods and Operators

• What if we want to print an instance


By using print(c) ?
→ Try it yourself multiple times and explain the results
• To print out an instance of a class,
E.g.: print(c)
→ Expected result: (4, 6)
⇒ use special method __str__
• Python calls __str__ method when used with print on class object
• We can display in any format as we want with __str__ and print

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 20


2. Class and Abstraction | 2.3. Special Methods and Operators

class Coordinate(object) :
def __init__(self, x, y) : # Initialize an object
self.x = x
self.y = y
def distance(self, other) :
x_diff_sq = (self.x - other.x)**2
y_diff_sq = (self.y - other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
def __str__(self) :
return "Object's coordinate (" + str(self.x) + "," + str(self.y) + ")"
Name of
special method
Format the string that will be
• Now, try print(c) displayed when using print

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 21


2. Class and Abstraction | 2.3. Special Methods and Operators

• What if we want to sum two Coordinate objects → use __add__


class Coordinate(object) :
def __init__(self, x, y) : # Initialize an object
self.x = x
self.y = y
def distance(self, other) :
x_diff_sq = (self.x - other.x)**2
y_diff_sq = (self.y - other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
def __str__(self) :
return "Object’s coordinate (" + str(self.x) + "," + str(self.y) + ")"
def __add__(self, other) :
return Coordinate(self.x + other.x, self.y + other.y)

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 22


2. Class and Abstraction | 2.3. Special Methods and Operators

• Special operators
• +, -, ==, >, <, len(), print and many more
• Special methods for special operators
• Define methods with double underscore before and after
__add__(self, other) → self + other
__sub__(self, other) → self – other
__eq__(self, other) → self == other?
__lt__(self, other) → self < other?
__len__(self) → len(self)
__str__(self) → print(self)
• Reference and help:
https://docs.python.org/3/reference/datamodel.html#basic-customization

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 23


2. Class and Abstraction | 2.4. Finger Exercise

• Create a new type to represent a number as a fraction


• Internal representation is two integers
• Numerator
• Denominator
• Interface a.k.a. methods a.k.a how to interact with Fraction objects
• Add, subtract
• Print representation
• Convert to a float
• Invert the fraction

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 24


3. Inheritance | 3.1. Features of Inheritance in OOP

• Many data types have common properties with other types


• Inheritance provides a convenient mechanism for building groups of
related abstractions.
• Programmers can create type hierarchy → each type inherits attributes
from the types above.
• In Python, class object is the top of hierarchy, the superclass. The
lower classes in the hierarchy are called subclass, which can:
• Add new attributes
• Override, i.e., replace the attributes of the superclass

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 25


3. Inheritance | 3.2. Creating a Hierarchy

• Using Class and Inheritance to keep track of students and faculty

Class Person

Class Class Class


HUSTPerson NEUPerson HUCEPerson

Class Class Class


HUSTStaff HUSTLecturer HUSTStudent

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 26


3. Inheritance | 3.2. Creating Hierarchy

• Class Person – the superclass Reserved


class Person(object)
def __init__(self, fullname=""):
self.name = fullname
self.firstname = NameIndentify(fullname)[0] # can call a function inside class
self.lastname = NameIndentify(fullname)[1]
self.birthday = None
# write your own NameIndentify function to extract last/first name
# write the following method
def set_name(self, fullname):
def get_name(self):
def get_firstname(self):
def get_lastname(self):
def set_birthday(self, birthdate): # import datetime
def get_age(self): # return years of age
def __lt__(self, other):
def __str__(self):

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 27


3. Inheritance | 3.2. Creating Hierarchy

• Class HUSTPerson – the subclass


class HUSTPerson(Person):
def __init__(self,fullname = ""):
Inheritance:
Person.__init__(self, fullname) The subclass inherits
the __init__ method of
def speak(self): the superclass
print("One love. One future")
Other methods of
Test: superclass are inherited
as well
NVA = HUSTPerson(“Nguyen Van A”)
print(NVA)
The method __str__ is not defined in HUSTPerson
but inherited from class Person
EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 28
3. Inheritance | 3.2. Creating Hierarchy

• Class HUSTStaff – a subclass


class HUSTStaff(HUSTPerson):
class nextStaffIDNum = 0
variable def __init__(self,fullname = "", department = ""):
increased HUSTPerson.__init__(self,fullname)
whenever self.department = department
an instance self.StaffIDNum = HUSTStaff.nextStaffIDNum
is created HUSTStaff.nextStaffIDNum += 1
def get_ID(self):
return self.StaffIDNum
def set_department(self, department):
self.department = department
def get_department(self):
return self.department Inherit and
def __lt__(self, other): expandable
return self.StaffIDNum < other.StaffIDNum
def __str__(self):
return Person.__str__(self) + "\nDepartment: " + self.department

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 29


3. Inheritance | 3.2. Creating Hierarchy

Write the other two classes (similar to HUSTStaff class)


• Class HUSTLecturer
• Subclass of HUSTPerson
• Use nextLecIDNum and LecIDNum for ID
• Use department for __init__
• Class HUSTStudent
• Subclass of HUSTPerson
• Use nextStuIDNum and StuIDNum for ID
• Use major for __init__

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 30


3. Inheritance | 3.2. Creating Hierarchy

• Test with the following code


P1 = Person("Nguyen Van Anh")
P1.set_birthday(datetime.date(1983, 3, 4))
P2 = HUSTLecturer("Nguyen Van Be")
P2.set_birthday(datetime.date(1983, 3, 4))
P2.set_department("Dept. of Automation Engineering")
P3 = HUSTLecturer("Nguyen Van Be")
P3.set_birthday(datetime.date(1996,12,5))
P3.set_department("Dept. of Communication")
P4 = HUSTStudent("Le Van Chien")
P4.set_birthday(datetime.date(2003,5,23))
P4.set_major("Control and Automation")
# Explain the result of the following lines of code
print("P1 < P2:", P1 < P2)
print("P3 < P2:", P3 < P2)
print("P1 < P4:", P1 < P4)
print("P4 < P1:", P4 < P1)
print("P3 < P4:", P3 < P4)

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 31


3. Inheritance | 3.2. Creating Hierarchy

• Want to change the class of P1 (currently type Person)?


P1 = Person("Nguyen Van Anh") # initially, a Person type object
P1.set_birthday(datetime.date(1983, 3, 4))

print(type(P1))
P1.__class__ = HUSTStaff # change to class HUSTStaff
P1.speak() # can speak as HUSTPerson
print(type(P1))
P1.set_department("Department of Personel") # can set department
# as HUSTStaff

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 32


4. Encapsulation and Information Hiding | 4.1. Encapsulation

• The data (variables) and methods are bundled within one unit (class)
• When you have attributes that are invisible from outside of the object:
• Can work with attributes by methods → use dot ‘.‘ notation
• The popular methods are getter and setter
• E.g.: set_name(self, fullname), get_name(self)
• Can assign the attribute read-only or not visible at all
• Encapsulation allows to hide specific information and control access to
the object’s internal state.
⇒ also called information hiding

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 33


4. Encapsulation and Information Hiding | 4.1. Encapsulation

• Example of grade of student management


class Grades(object):
"""Create empty grade book"""
def __init__(self):
self.students = [] # list of student
self.grades = {} # a dictionary, map student’s ID to grade
self.isSorted = True
def addStudent(self,student):
"""Add a student into the book"""
if student in self.students: #check if added -> raise error
raise ValueError('Duplicate student')
self.students.append(student) #add student to the list
self.grades[student.get_ID()] = []
self.isSorted = False

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 34


4. Encapsulation and Information Hiding | 4.1. Encapsulation

• Example of grade of student management (cont.)


def addGrade(self,student,grade):
student_ID = student.get_ID()
if student_ID in self.grades:
self.grades[student_ID].append(grade)
else:
raise ValueError('Student is not in the list')
def getGrades(self,student):
student_ID = student.get_ID()
if student_ID in self.grades:
return self.grades[student_ID][:]
else:
raise ValueError('Student is not in the list')
def getStudent(self):
return self.students[:]

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 35


4. Encapsulation and Information Hiding | 4.1. Encapsulation

• Now, create a function that generates a list of grade of students


def GradeReport(StudentList):
"""Make a report of grade when providing a list of students"""
report = "" # empty report
for i in StudentList.getStudent(): # each i is a student object
tot_score = 0
num_grade = 0
for s in StudentList.getGrades(i): # can extract attribute of i
tot_score += s
num_grade += 1
report = report + str(i.get_name()) + " mean of grade: "\
+ str(tot_score/num_grade) +"\n"
return report

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 36


4. Encapsulation and Information Hiding | 4.1. Encapsulation

• Then create a list of students and generate the report. (Note: import
classes in inheritance). Something like this, for example.
P1 = HUSTStudent("Nguyen Van Anh") # create students, type:HUSTStudent
P2 = HUSTStudent("Nguyen Van Be")
P3 = HUSTStudent("Tran Van Chinh")
P4 = HUSTStudent("Le Van Chien")
student_list = Grades() # Create a list of students, type: Grades
student_list.addStudent(P3)
student_list.addGrade(P3,7)
student_list.addStudent(P4) using dot ‘.’ notation for
student_list.addGrade(P4,9) working with attributes of
student_list.addStudent(P1) objects
student_list.addGrade(P1,10) ⇒ Encapsulation
student_list.addStudent(P2)
student_list.addGrade(P2,8.5)
print(GradeReport(student_list))

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 37


4. Encapsulation and Information Hiding | 4.2. Information Hiding

• Information hiding is one of the keys to modularity


• Protect the code from breaking by the change in the implementation of the
class
• In C++, information hiding can be done by creating a class private
• The user can access attributes/data through object’s methods
• In Python, a naming convention is used to make attributes invisible
• Attribute/data starts with ‘__’ and ends with ‘__’: visible outside of the class
E.g.: __init__, __str__, __add__
• Attribute/data starts with ‘__’ but doesn’t end with ‘__’: invisible
E.g.: __a, __invisible

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 38


4. Encapsulation and Information Hiding | 4.2. Information Hiding

• Example:
class infoHiding(object): test = infoHiding()
def __init__(self): print(test.visible)
self.visible = 'Look at me' print(test.__alsoVisible__)
self.__alsoVisible__ = 'Look at me, too' print(test.__invisible)
self.__invisible = 'Can\'t see me directly'
def printVisible(self): test.printInvisible
print(self.visible) test.__printInvisible__()
def printInvisible(self): test.__printInvisible()
print(self.__invisible)
def __printInvisible(self): subtest = subclass()
print(self.__invisible)
def __printInvisible__(self):
print(self.__invisible)
class subClass(infoHiding):
def __init__(self):
print('from subclass', self.__invisible)
EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 39
5. Polymorphism | 5.1. Examples on Polymorphism

• Polymorphism in operators, e.g. addition operator


num_1 = 5
num_2 = 6.0
print(num_1+num_2) One operator,
different usages and
str_1 = "Hanoi" different types
str_2 = "Capital"
print(str_1 + " " + str_2)
Output:
11.0
Hanoi Capital

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 40


5. Polymorphism | 5.1. Examples on Polymorphism

• Polymorphism in functions, e.g. len() function


My_list = ["Hanoi", "Hai Phong", "Ha Long", "Lang Son"]
My_string = "The Hanoi Capital"
My_dict = {"Capital":"Hanoi", "City":"Hai Phong", "Province":"Quang Ninh"}
print(len(My_list))
print(len(My_string)) One function,
print(len(My_dict)) different data types
Output: str
Length of string
4
17 len()
list
Number of items
3
dict
Number of keys

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 41


5. Polymorphism | 5.2. Polymorphism in OOP

5.2.1. Class Polymorphism


class Cat(object): The two classes have a similar
def __init__(self, name, age): structure and the same method names
self.name = name
self.age = age
def info(self):
print("I\'m a",self.age,"years old cat. My name is",self.name)
def speak(self):
print("Meow")
class Dog(object):
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print("I\'m a",self.age,"years old dog. My name is",self.name)
def speak(self):
print("Woof")

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 42


5. Polymorphism | 5.2. Polymorphism in OOP

• Using the created classes Note:


My_cat = Cat("Kitty", 3) - No common super class or linked
My_dog = Dog("Billy", 5)
classes
for animal in [My_cat, My_dog]:
- The two different objects are
animal.speak()
animal.info() packed into a list
animal.speak() - Iterate through a common animal
variable
Output: - The animal variable can be any
Meow
type
I'm a 3 years old cat. My name is Kitty
⇒ This is possible due to
Meow
Woof
polymorphism
I'm a 5 years old dog. My name is Billy
Woof

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 43


5. Polymorphism | 5.2. Polymorphism in OOP

5.2.2. Method Overloading


• Two or more methods have the same name but different numbers of
parameters or different types of parameters, or both.
E.g. (pseudo code):
define function add(arg_1, arg_2)
return arg_1 + arg_2
define function add(arg_1, arg_2, arg_3)
return arg_1 + arg_2 + arg_3
call functions: add(4,5)
add(5,6,7)
• Python does not support method overloading by default (Give it a try!), but we
can work around.

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 44


5. Polymorphism | 5.2. Polymorphism in OOP

5.2.3. Polymorphism and Inheritance – Method Overriding


• Redefine methods for a subclass that are already defined in the
superclass
class vehicle(object): class plane(vehicle):
def __init__(self, brand, model): def move(self):
self.brand = brand print("Fly!")
self.model = model redefined
def move(self): My_car = car("BMW", "X3")
print("Move!") My_boat = boat("Princess Yacht", "s65")
already defined
class car(vehicle): My_plane = plane("Airbus","A320")
pass for veh in [My_car, My_boat, My_plane]:
class boat(vehicle): print(veh.brand)
def move(self): print(veh.model)
print("Sail!") veh.move()
redefined (override the method)
EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 45
End of Chapter 4

46

You might also like