1 of 62

Advanced Python Programming

Hoang-Giang Cao (高黃江)

Sep 2023

2 of 62

4 Pillars of OOP

  • 4 Pillars of OOP
    • Abstraction
    • Encapsulation
    • Inheritance
    • Polymorphism

3 of 62

Basic Python

Homework 2

  • Only 17/25 students submitted.
  • Deadline: 23:59PM 11/23
  • To: chgiang24@mail.mcu.edu.tw
  • 70% score

4 of 62

Basic Python

Homework 1

  • Only 26/28 students submitted.
  • Deadline: 23:59PM 11/23
  • To: chgiang24@mail.mcu.edu.tw
  • 70% score

5 of 62

Basic Python

Midterm

  • Who score lower than 70pts can re-submit midterm (3 students)
  • Deadline: 23:59PM 11/23
  • To: chgiang24@mail.mcu.edu.tw
  • 70% score

6 of 62

Basic Python

Homework 3

  • Deadline: 23:59PM 11/23 (NOV 23rd)
  • To: chgiang24@mail.mcu.edu.tw
  • Topic: OOP

7 of 62

Basic Python

Thanksgiving event

2 Extra Homeworks - Not required to do. But, attending each of them:

  • Maximum: + 3 final score
  • Attending: + 1 final score
    • Only need to attend/submit
    • No matter you are doing correct or not

8 of 62

4 Pillars of OOP

  • Four-pillars of object-oriented programming
  • 物件導向程式設計可以讓程式碼實現四個特殊性質,俗稱四大支柱
    • 抽象(Abstraction)
    • 封裝(Encapsulation)
    • 繼承(Inheritance)
    • 多型(Polymorphism)

9 of 62

4 Pillars of OOP

抽象

封裝

繼承

多型

10 of 62

Class

class Car()

The concept of a car

pattern/design

brand

color

shape

length

.

etc

move ()

steering ()

stop ()

open_light()

.

etc

Attribute/property

  • Feature of the object
  • Represent the object
  • How the object look likes

Method/behaviors

  • What the object can do
  • What we can do with the object

Difference instance has different value for each attribute: different in appearance

All instances of the same class has the same method/behaviors

Each car has different name, color, shape. But all cars can move, steering, stop, open_light, etc

Instances/object

Attribute

Method

11 of 62

Abstraction (抽象)

  • Only show the necessary methods (interface) to operate with the object

  • Abstraction is about hiding the complex implementation.
  • Give a simple user interface to the user.
  • Make the system more user-friendly.

抽象在物件導向程式設計中隱藏成員屬性與方法實作細節的機制,讓使用者能方便地使用功能而不需要了解細節

12 of 62

Abstraction

  • Only show the necessary methods (interface) to operate with the object

You press the “Power” button

to turn on the computer

without caring about the mechanism behind making it actually work

interface

operate

“Power” button

13 of 62

Abstraction

  • Only show the necessary methods (interface) to operate with the object

What we need to know is that pressing the Power button, and the PC will turn on, go to the OS

How does it work (hardwares, software), we don’t (really need to) know

“Power” button

Display to the screen

mechanism behind

14 of 62

Abstraction

Hidden mechanism behind

=

Return the result

3/7 + 7/3 = ?

Calculator

15 of 62

Abstraction

mechanism behind

Function remove_oldest_car() to remove the oldest car

List of cars

List of cars

10 years

15 years

30 years

20 years

5 years

interface

operator

  • Sort car by year
  • Select the oldest
  • Remove the oldest car

hidden

16 of 62

Abstraction

username

password

birth_year

Attribute

Method

amount_TWD

amount_USD

check_valid_deposit()

check_valid_pass()

Other internal methods

get_total()

17 of 62

Abstraction

username

password

birth_year

Attribute

Method

amount_TWD

amount_USD

check_valid_deposit()

check_valid_pass()

Other internal methods

get_total()

amount_TWD

+

amount_USD*30

User

Client

Frontend

Call the function

Get the return result

18 of 62

Abstraction

Encapsulation

Back-end

Front-end

Client

User

Send request/input

Get result/output

Internet

Blackbox to the user/client/front-end

Database

API

(public functions)

backend

19 of 62

Abstraction

Encapsulation

Back-end

Front-end

Client

User

Send request/input

Get result/output

Internet

Blackbox to the user/client/front-end

API

(public functions)

Database

20 of 62

Bank account implementation

class BankAccount:

withdraw_rate = 0.005 #0.5#

def __init__(self,username,password):

#userbank information

self.username = username

self.password = password

#bank account

self.account_TWD =0

self.transactions=[] #list of transaction

Class Attributes:

  1. withdraw_rate:
    • A class-level attribute that represents the fee charged on withdrawals. It is set to 0.005, meaning a 0.5% fee will be applied to withdrawals.

Instance Attributes (defined in the __init__ constructor):

  1. username:
    • Stores the username associated with the bank account. This is provided when an instance of BankAccount is created.
  2. password:
    • Stores the password for the bank account. This is provided when an instance of BankAccount is created.
  3. account_TWD:
    • Represents the balance in the account, initially set to 0. The balance is stored in New Taiwan Dollars (TWD).
  4. transactions:
    • A list that stores the history of transactions made on the account. Initially, it is an empty list.

21 of 62

class BankAccount:

withdraw_rate = 0.005 #0.5#

def __init__(self,username,password):

#userbank information

self.username = username

self.password = password

#bank account

self.account_TWD =0

self.transactions=[] #list of transaction

def withdraw(self,request_amount_TWD):

withdraw_fee = request_amount_TWD*BankAccount.withdraw_rate

if (self.account_TWD >= request_amount_TWD+withdraw_fee):

print("Succesfull transaction!")

print("Withdraw ",request_amount_TWD,"NTD. withdraw free:",withdraw_fee,"NTD")

self.account_TWD -= (request_amount_TWD+withdraw_fee)

else:

print("Insufficient money! Transaction Failed!"

#Client side # Bank Officer#withdraw

print("Before transaction:", acc_1.account_TWD,"NTD")

acc_1.withdraw(2000)

print("After transaction:", acc_1.account_TWD,"NTD")

#user create and deposit

acc_1 = BankAccount("KO","1234")

#deposit

acc_1.account_TWD = 3000

Class implementation

Backend

You only need to call the function, no need to know how does it work (back-end responsibility)

Bank Officer

Client

User

Deposit (Init)

22 of 62

class BankAccount:

withdraw_rate = 0.005 #0.5#

def __init__(self,username,password):

#userbank information

self.username = username

self.password = password

#bank account

self.account_TWD =0

self.transactions=[] #list of transaction

def withdraw(self,request_amount_TWD):

withdraw_fee = request_amount_TWD*BankAccount.withdraw_rate

if (self.account_TWD >= request_amount_TWD+withdraw_fee):

print("Succesfull transaction!")

print("Withdraw ",request_amount_TWD,"NTD. withdraw free:",withdraw_fee,"NTD")

self.account_TWD -= (request_amount_TWD+withdraw_fee)

else:

print("Insufficient money! Transaction Failed!"

#Client side # Bank Officer#withdraw

print("Before transaction:", acc_1.account_TWD,"NTD")

acc_1.withdraw(1000)

print("After transaction:", acc_1.account_TWD,"NTD")

#user create and deposit

acc_1 = BankAccount("KO","1234")

#deposit

acc_1.account_TWD = 3000

Class implementation

Backend

Bank Officer

Client

User

Deposit (init)

23 of 62

class BankAccount:

withdraw_rate = 0.01 #0.5#

def __init__(self,username,password):

#userbank information

self.username = username

self.password = password

#bank account

self.account_TWD =0

self.transactions=[] #list of transaction

def withdraw(self,request_amount_TWD):

withdraw_fee = request_amount_TWD*BankAccount.withdraw_rate

if (self.account_TWD >= request_amount_TWD+withdraw_fee):

print("Succesfull transaction!")

print("Withdraw ",request_amount_TWD,"NTD. withdraw free:",withdraw_fee,"NTD")

self.account_TWD -= (request_amount_TWD+withdraw_fee)

else:

print("Insufficient money! Transaction Failed!"

#Client side # Bank Officer#withdraw

print("Before transaction:", acc_1.account_TWD,"NTD")

acc_1.withdraw(1000)

print("After transaction:", acc_1.account_TWD,"NTD")

#user create and deposit

acc_1 = BankAccount("KO","1234")

#deposit

acc_1.account_TWD = 3000

Class implementation

Backend

Bank Officer

Client

User

Deposit (init)

If the fee rate change, the front-end still be correct

Nothing change in the code of front-end

24 of 62

class BankAccount:

withdraw_rate = 0.01 #0.5#

def __init__(self,username,password):

#userbank information

self.username = username

self.password = password

#bank account

self.account_TWD =0

self.transactions=[] #list of transaction

def withdraw(self,request_amount_TWD):

withdraw_fee = request_amount_TWD*BankAccount.withdraw_rate

if (self.account_TWD >= request_amount_TWD+withdraw_fee):

print("Succesfull transaction!")

print("Withdraw ",request_amount_TWD,"NTD. withdraw free:",withdraw_fee,"NTD")

self.account_TWD -= (request_amount_TWD+withdraw_fee)

else:

print("Insufficient money! Transaction Failed!"

#Client side # Bank Officer#withdraw

print("Before transaction:", acc_1.account_TWD,"NTD")

acc_1.withdraw(1000)

print("After transaction:", acc_1.account_TWD,"NTD")

#user create and deposit

acc_1 = BankAccount("KO","1234")

#deposit

acc_1.account_TWD = 3000

Class implementation

Backend

Bank Officer

Client

User

Deposit

Or if we modify/update anything inside the withdraw function, the client slide still be the same

25 of 62

class BankAccount:

def __init__(self,username,password):

#userbank information

self.username = username

self.password = password

#bank account

self.account_TWD =0

self.transactions=[] #list of transaction

#make a withdraw

withdraw_rate = 0.05

request_amount_TWD = 1000

#Client side # Bank Officer#withdraw

print("Before transaction:", acc_1.account_TWD,"NTD")

withdraw_fee = request_amount_TWD*withdraw_rate

if (acc_1.account_TWD >= request_amount_TWD+withdraw_fee):

print("Succesfull transaction!")

print("Withdraw ",request_amount_TWD,"NTD. withdraw free:",withdraw_fee,"NTD")

acc_1.account_TWD -= (request_amount_TWD+withdraw_fee)

else:

print("Insufficient money! Transaction Failed!")

print("After transaction:", acc_1.account_TWD,"NTD")

Class implementation

Backend

Bank Officer

Client

User

If we do the code in the client (front-end), client need to update by themself (not convenient, or not permission)

26 of 62

Abstraction

  • Only show the necessary methods (interface) to operate with the object

  • Abstraction is about hiding the complex implementation.
  • Give a simple user interface to the user.
  • Make the system more user-friendly.

27 of 62

Encapsulation

28 of 62

Encapsulation(封裝)

  • Grouping the attribute and methods of the object into a single unit
  • Protect the important data (attribute) accessed by outside code
  • Maintaining data consistency

Capsule

Encapsulation

Binding attribute and method in to a single unit

封裝是物件導向程式設計中隱藏資料與函式實作的技巧。

29 of 62

Encapsulation

username

password

birth_year

Attribute

Method

amount_TWD

amount_USD

check_valid_deposit()

check_valid_pass()

Other internal methods

deposit_TWD()

deposit_USD()

set_password()

get_total()

Capsule

Encapsulation

Binding attribute and method in to a single unit

30 of 62

Problem of protecting data

username

password

birth_year

Attribute

Method

amount_TWD

amount_USD

check_valid_deposit()

check_valid_pass()

Other internal methods

deposit_TWD()

deposit_USD()

set_password()

get_total()

Front-end

Client

User

Send request/input

Get result/output

Should not happen

31 of 62

Problem of protecting data

username

password

birth_year

Attribute

Method

amount_TWD

amount_USD

check_valid_deposit()

check_valid_pass()

Other internal methods

deposit_TWD()

deposit_USD()

set_password()

get_total()

Front-end

Client

User

Send request/input

Get result/output

Should not happen

32 of 62

Bank account implementation

class BankAccount:

withdraw_rate = 0.005 #0.5#

def __init__(self,username,password):

#userbank information

self.username = username

self.password = password

#bank account

self.account_TWD =0

self.transactions=[] #list of transaction

Class Attributes:

  • withdraw_rate:
    • A class-level attribute that represents the fee charged on withdrawals. It is set to 0.005, meaning a 0.5% fee will be applied to withdrawals.

Instance Attributes (defined in the __init__ constructor):

  • username:
    • Stores the username associated with the bank account. This is provided when an instance of BankAccount is created.
  • password:
    • Stores the password for the bank account. This is provided when an instance of BankAccount is created.
  • account_TWD:
    • Represents the balance in the account, initially set to 0. The balance is stored in New Taiwan Dollars (TWD).
  • transactions:
    • A list that stores the history of transactions made on the account. Initially, it is an empty list.

33 of 62

Encapsulation

Bank officer 1

(client)

username

password

account_TWD

Get user.password??

Admin created

Or user register

database

Data protection

Username

Password

KO

1234

Alex

ILoveYou

Tom

KissYou

BankAccount

34 of 62

Bank officer 1

(client)

username

password

account_TWD

Admin created

Or user register

database

Client/frontend

Server/backend

Database

Get user.password??

Username

Password

KO

1234

Alex

ILoveYou

Tom

KissYou

result

BankAccount

35 of 62

Username

Password

KO

1234

Alex

ILoveYou

Tom

KissYou

Bank officer 1

(client)

username

password

account_TWD

Admin created

Or user register

database

Client/frontend

Server/backend

Database

result

NO PERMISSION TO DO THAT!!!!

Get user.password??

BankAccount

36 of 62

Encapsulation

username

password

birth_year

Attribute

Method

amount_TWD

amount_USD

Abstraction

check_valid_deposit()

check_valid_pass()

Other internal methods

deposit_TWD()

deposit_USD()

set_password()

get_total()

User access

User access

X

Sensitive information

37 of 62

Abstraction

Encapsulation

Attributes

Methods

Front-end

Client

User

Send request/input

Get result/output

Internet

API

(public functions)

Database

38 of 62

Encapsulation

username

password

birth_year

Attribute

Method

amount_TWD

amount_USD

Abstraction

check_valid_deposit()

check_valid_pass()

Other internal methods

deposit_TWD()

deposit_USD()

set_password()

get_total()

User access

User access

X

39 of 62

Encapsulation

Abstraction

Front-end

Client

User

Internet

Blackbox to the user/client/front-end

API

(public functions)

Database

Attribute

(data)

Methods

(functions)

Send request/input

Get result/output

40 of 62

Encapsulation

Abstraction

Front-end

Client

User

Send request/input

Get result/output

Internet

Blackbox to the user/client/front-end

API

(public functions)

Database

Attribute

(data)

Methods

(functions)

41 of 62

Encapsulation

  • How to protect the attribute? -> make it be private
  • Only accessible inside the class definition
  • Using double underscore “__to set a attribute or method be private

42 of 62

Encapsulation

Bank officer 1

(client)

username

password

account_TWD

Get user.password??

Admin created

Or user register

database

Data protection

Username

Password

KO

1234

Alex

ILoveYou

Tom

KissYou

BankAccount

43 of 62

Bank officer 1

(client)

username

password

account_TWD

Admin created

Or user register

database

Client/frontend

Server/backend

Database

Get user.password??

Username

Password

KO

1234

Alex

ILoveYou

Tom

KissYou

result

BankAccount

44 of 62

Abstraction

Encapsulation

Attributes

Methods

Front-end

Client

User

Send request/input

Get result/output

Internet

API

(public functions)

Database

45 of 62

Username

Password

KO

1234

Alex

ILoveYou

Tom

KissYou

Bank officer 1

(client)

username

password

account_TWD

Admin created

Or user register

database

Client/frontend

Server/backend

Database

result

NO PERMISSION TO DO THAT!!!!

Get user.password??

BankAccount

46 of 62

Encapsulation

Abstraction

Front-end

Client

User

Internet

Blackbox to the user/client/front-end

API

(public functions)

Database

Attribute

(data)

Methods

(functions)

Send request/input

Get result/output

47 of 62

Encapsulation

Abstraction

Front-end

Client

User

Send request/input

Get result/output

Internet

Blackbox to the user/client/front-end

API

(public functions)

Database

Attribute

(data)

Methods

(functions)

48 of 62

Username

Password

KO

1234

Alex

ILoveYou

Tom

KissYou

Bank officer 1

(client)

username

password

account_TWD

Admin created

Or user register

database

Client/frontend

Server/backend

Database

Get user.password??

Set password be private

self.__password

Get error result

NO PERMISSION TO DO THAT!!!!

49 of 62

BankAccount

username

password

account_TWD = 20

transaction[]

Transaction

Amount

1

5

2

10

3

5

= 20

account_TWD

consistency

Transaction

Amount

1

5

2

10

3

5

database

Bank officer 1

50 of 62

Encapsulation

BankAccount

username

password

account_TWD = 20

transaction[]

Transaction

Amount

1

5

2

10

3

5

= 20

account_TWD

consistency

Bank officer 1

Data consistency

51 of 62

BankAccount

username

password

account_TWD = 20

transaction[]

Transaction

Amount

1

5

2

10

3

5

= 20

account_TWD

consistent

Bank officer 1

Transaction

Amount

1

5

2

10

3

5

database

consistent

52 of 62

username

password

account_TWD = 20

transaction[]

user_1.account_TWD = 1000000???

BankAccount

Transaction

Amount

1

5

2

10

3

5

= 1000000

account_TWD

Bank officer 1

Transaction

Amount

1

5

2

10

3

5

database

53 of 62

username

password

account_TWD = 20

transaction[]

user_1.account_TWD = 1000000???

BankAccount

Transaction

Amount

1

5

2

10

3

5

= 1000000

account_TWD

inconsistent!!!

Bank officer 1

Transaction

Amount

1

5

2

10

3

5

database

inconsistent!!!

NO PERMISSION TO DO THAT!!!!

54 of 62

username

password

account_TWD = 20

transaction[]

BankAccount

Transaction

Amount

1

5

2

10

= 20

account_TWD

inconsistent!!!

Bank officer 1

Transaction

Amount

1

5

2

10

database

Forget to add transaction

Mising adding transaction

inconsistent!!!

55 of 62

username

password

account_TWD = 20

transaction[]

BankAccount

Transaction

Amount

1

5

2

10

3

5

= 15

account_TWD

inconsistent!!!

Bank officer 1

Transaction

Amount

1

5

2

10

3

5

database

Forget to update total amount

inconsistent!!!

Missing update account_TWD

56 of 62

username

password

account_TWD = 20

transaction[]

BankAccount

Bank officer 1

API

(public functions)

Make attributes be private, provide public functions (API) for user to operate

No more direct access to the attribute

Solution

So we need the deposit function

To ensure the consistency of adding and updating

57 of 62

username

password

account_TWD = 20

transaction[]

BankAccount

Bank officer 1

API

(public functions)

Make attributes be private, provide public functions (API) for user to operate

Solution

Use the provided pubic function to deposit money

Transaction

Amount

1

5

2

10

3

15

account_TWD = 5

account_TWD = 15

account_TWD = 20

Transaction

Amount

1

5

2

10

3

15

account_TWD = 5

account_TWD = 15

account_TWD = 20

Alway consistent

58 of 62

Data validation

Data validation

Direct access to the attribute

Access through provided public function

Invalid data

59 of 62

Make attributes be private, provide public functions (API) for user to operate

Transaction

Amount

1

5

2

10

3

15

account_TWD = 5

account_TWD = 15

account_TWD = 20

Alway consistent

How to access the needed attributes: account_TWD, transactions?

If they are private?

No more direct access to the attribute

60 of 62

Provided some public function that allow the user get the private attributes

Transaction

Amount

1

5

2

10

3

15

account_TWD = 5

account_TWD = 15

account_TWD = 20

Alway consistent

How to access the needed attributes: account_TWD, transactions?

If they are private?

Access private attribute through public functions (API) (similar to getter/setter in c++)

Solution

You provided some public function that allow the user get the private attributes

Client can get value, but can not set or assign value

61 of 62

Encapsulation(封裝)

  • Encapsulate the attribute and method in a single unit (class)
  • Protect important/sensitive data -> by set them to be private
  • Maintain data consistency -> by fully control the processing data
  • Maintain data validation
  • Provide public functions (API) for user to operate with the system

封裝是物件導向程式設計中隱藏資料與函式實作的技巧。

62 of 62