Python 2 - P3 OOP PDF
Python 2 - P3 OOP PDF
OOP
TS. NGUYỄN HOÀNG LONG
0916666384
[email protected]
OBJECT ORIENTED PROGRAMMING
An object contains data and behavior The concept of OOP in Python focuses
on developing reusable code. This
concept is also known as DRY (Don't
Repeat Yourself).
2
OBJECT ORIENTED PROGRAMMING
OOPs take time to get used to it. The Development is faster and cheaper,
concept may be too complex for with better software maintainability
beginners
3
4 CLASS VS
OBJECT
• Class: can be defined as a template
which describes the data and
methods of a group of object
6
DECLARE A CLASS
7
INSTANTIATE AN OBJECT
• Instantiate an object
object = class-name (data1, data2, …)
8
INSTANTIATE AN OBJECT
• Instantiate an object
object = class-name (data1, data2, …)
9
INSTANTIATE AN OBJECT
• Instantiate an object
object = class-name (data1, data2, …)
10
RUN
11
PRACTISE 2-1
13
INSTANCE METHODS
14
RUN
15
PRACTISE 2-2
17
RUN
18
PRACTISE 2-3
Write a Python program to create a class
of a desk of cards
20
DUNDER METHOD
21
DUNDER METHOD
Dunder method is also called magic method. Dunder method is used to customized the built-in
method of classes
22
DEFAULT GREATER THAN FUNCTION
23
CUSTOMIZE THE
GREATER THAN FUNCTION
24
PRACTISE 2-4
The Deck class should have a deal
method to deal a single card from the
deck
26
CUSTOMISE DEL() FUNCTION
27
PRACTISE 2-5
29
UPGRADE AND ADD MORE METHOD
• Add more code to print_info(self) method
30
ADD CLASS PASSENGER
31
UPGRADE MAIN FUNCTION
32
RUN
33
ACCESS CLASS ATTRIBUTE
34
RUN
35
PRACTISE 2-6
The sub-class inherits all the data and A class (often called a super class) can
methods of the parent class. The be inherited by another class (often
inherited components can be extended. called a sub-class or child-class)
New data and methods can be also
added into the sub-class
37
AIRLINE PROJECT
• An airline company offers two types of flight:
• Cheap flight
• Normal flight
• Normal flight:
✓ passengers can get customer points for the
purchased tickets
✓ Provide meal for passengers
• Cheap flight:
✓ Passengers do not get customer points for the
purchased tickets
✓ Passenger can get one bottle of water
38
SOLUTION
39
INHERITANCE
CHEAP FLIGHT – NORMAL FLIGHT
40
TEST INHERITANCE
41
CHALLENGE
The private property is denoted by a "-" Those types of variables are called
or "__" as a prefix private variables
43
NO ENCAPSULATION
44
ENCAPSULATION
DECLARE PRIVATE VARIABLE
45
ASSIGN NEW VALUE
FOR PRIVATE VARIABLE
46
ENCAPSULATION
ADD CHANGE_DRINK METHOD
47
POLYMORPHISM
For example: the input for the len The coding process is easier and more
function can be either a string or a a list efficient when using Polymorphism in
some cases.
48
POLYMORPHISM - 1
49
POLYMORPHISM - 2
50
POLYMORPHISM – 3
51
POLYMORPHISM - 4
52
POLYMORPHISM - 5
53
POLYMORPHISM - 6
54