Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Lecture 9 TA Object Oriented Programming

以下是模擬ATM機的步驟: 1. 創建Account類別,包含id, password, balance屬性 2. 初始化一個帳戶陣列,包含幾個Account物件,每個帳戶的初始餘額為100 3. 輸入使用者id和密碼驗證 4. 顯示主選單,包含查看餘額,提款,存款,退出等選項 5. 根據使用者選擇的選項,

Uploaded by

tzhr87yng5
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Lecture 9 TA Object Oriented Programming

以下是模擬ATM機的步驟: 1. 創建Account類別,包含id, password, balance屬性 2. 初始化一個帳戶陣列,包含幾個Account物件,每個帳戶的初始餘額為100 3. 輸入使用者id和密碼驗證 4. 顯示主選單,包含查看餘額,提款,存款,退出等選項 5. 根據使用者選擇的選項,

Uploaded by

tzhr87yng5
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Computer Programming

Reporter : 李威德

Object-oriented Programming

Micro Optics Device Laboratory


MODEL
Outline
• Object-oriented Programming

1. Abstract

2. Encapsulation

3. Inheritance

4. Polymorphism

2022/11/16 Assistant: Chun-Yuan Fan


Overview of OOP Terminology
•Class − A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are
data members (class variables and instance variables) and methods, accessed via dot notation.
•Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's
methods. Class variables are not used as frequently as instance variables are.
•Data member − A class variable or instance variable that holds data associated with a class and its objects.
•Function overloading − The assignment of more than one behavior to a particular function. The operation performed varies by the types
of objects or arguments involved.
•Instance variable − A variable that is defined inside a method and belongs only to the current instance of a class.
•Inheritance − The transfer of the characteristics of a class to other classes that are derived from it.
•Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class
Circle.
•Instantiation − The creation of an instance of a class.
•Method − A special kind of function that is defined in a class definition.
•Object − A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and
instance variables) and methods.
•Operator overloading − The assignment of more than one function to a particular operator.
Abstract
• 物件導向程式設計(簡稱 OOP )是一種程式設計範式,它提供了
一種結構化程式的方法,以便將屬性和行為捆綁到單獨的物件中。

• Python 自誕生以來就是一種物件導向的語言。 因此,創建和使用


類別和物件非常簡單。

1. Define a Class
2. Creating Instance Objects
3. Accessing Attributes
4. Built-In Class Attributes

2022/11/16 Assistant: Chun-Yuan Fan


Define a class and Creating Instance Objects
Class definition Name Class parent

class NTUstudent (object): Variable to refer to an


instance of the class
def __init__(self, number):
Special method to What data initializes
create an instance
self.num= number a NTUstudent type

self.name = None Name is data attribute even


though an instance is not
initialized with it as a parameter
LEE=NTUstudent(“ 學號” )
One instance Mapped to self.num in class def

2022/11/16
Accessing Attributes
class NTUstudent(object):
def __init__(self, number):
self.num= number
self.name = None

def get_num(self):
return self.num
getters
def get_name(self):
return self.name

def set_num(self, newnum):


self.num= newnum

def set_name(self, newname=“”):


setters
self.name = newname

def __str__(self):
return “NTU ”+str(self.num)+“:”+str(self.name)

NTU=NTUstudent(“ 學號 ")
NTU.set_name(“XX")

print(NTU)

2022/11/16 Assistant: Chun-Yuan Fan


• 您可以使用以下函數,而不是使用普通語句來存取屬性 -
• getattr(obj, name[, default]) − 存取物件的屬性。
• hasattr(obj,name) - 檢查屬性是否存在。
• setattr(obj,name,value) − 設定屬性。 如果屬性不存在,則會建立它。
• delattr(obj, name) − 刪除屬性。

class XX(object):
def __init__(self,number):
self.number=number

def __str__(self):
return self.number + self.name

a=XX(“ 學號 ")

getattr(a,"number")
print(hasattr(a,"number"))
setattr(a,"year",8)
delattr(a, "year")
Built-In Class Attributes
每個 Python 類別都遵循內建屬性,可以像任何其他屬性一樣使用點運算子存取它們 -
__dict__ - 包含類別的名稱空間的字典。
__doc__ - 類別文檔字串或無(如果未定義)。
__name__ − 類別名稱。
__module__ - 定義類別的模組名稱。 此屬性在互動模式下為「 __main__ 」。

class XX(object):
"OOP"
def __init__(self,number):
self.number=number

def __str__(self):
return self.number + self.name

a=XX("d05941014")

print(XX.__doc__)
print(XX.__name__)
print(XX.__module__)
print(XX.__dict__)
Encapsulation
• This concept is also often used to hide the internal representation, or state, of an object from the
outside. This is called information hiding. The general idea of this mechanism is simple. If you have
an attribute that is not visible from the outside of an object, and bundle it with methods that provide
read or write access to it, then you can hide specific information and control access to the internal
state of the object.

https://medium.com/@ethan.reid.roberts/object-oriented-
fundamentals-polymorphism-and-encapsulation-8acff4357446

2022/11/16
Inheritance
class CPTA(NTUstudent):
def speak(self):
print("Hello, I am your TA")

def __str__(self):
return "NTU"+" Computer Programming " + str(self.num) + ":" + str(self.name)

class CPstudent(NTUstudent):
def speak(self):
print("OOP lecture!")

def __str__(self):
return "NTU"+" Computer Programming " + str(self.num) + ":" + str(self.name)

a=CPTA(“XX")
b=CPstudent(“YY")

CPTA
NTUstudent
CPstudent

2022/11/16
Subclass
__init__
class CPstudent(NTUstudent):
def __init__(self,number,age):
NTUstudent.__init__(self,number)
self.age=age

def speak(self):
print("OOP lecture!")

def __str__(self):
return "NTU"+" Computer Programming " + str(self.num) + ":" + str(self.name)

def test(self):
return self.age

b=CPstudent("b01234567",18)

2022/11/16
什麼是 self?
總歸一句話就是自己,跟英文的 self 是一樣的 ~
讓我們來看看以下的範例:
Polymorphism
• 多態性是 Python 中類別定義的重要功能,當您在類別或子類別中具有通用命名的方法
時,可以使用多態性。 這允許函數使用任何這些多型類別的對象,而無需了解類別之間的
差異。

• 多態性可以透過繼承來實現,子類別可以使用基底類別方法或重寫它們。

Speak

喵~ 汪汪 ~ 嗯!
Create your own class!
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
class Yuan(object):
def __init__(self,loction):
self.loc=loction

def CYF_plot(self):
img=pd.read_excel(self.loc)
plt.imshow(img)
plt.show()

def CYF_plot_3D(self):
img=pd.read_excel(self.loc)

fig = plt.figure()
ax = fig.gca(projection="3d")

x = np.linspace(1, img.shape[1], img.shape[1])


y = np.linspace(1, img.shape[0], img.shape[0])
X, Y = np.meshgrid(x, y)

pic = ax.plot_surface(X, Y, img)


plt.show()

loc="D:\CYF\Program\Python\Computer_programming_Course/2020\Lecture 6/field_xy.xlsx"

a=Yuan(loc)
a.CYF_plot()
2022/11/16
a.CYF_plot_3D() Assistant: Chun-Yuan Fan
Pycharm setting
• If you go to File -> Settings -> Project: YourProjectName -> Project Structure, you'll have a
directory layout of the project you're currently working in. You'll have to go through your
directories and label them as being either the Source directory for all your Source files, or as a
Resource folder for files that are strictly for importing.
可以用 pass 讓裡面是空的
Python 繼承
(Inheritance)

繼承
teansportation
多層繼承 (Multi-Level
Inheritance)
多重繼承 (Multiple
Inheritance)

此案例中,有很大的問題,因為 bird
跟 animal 兩個都為 DUCK 繼承的
class ,那麼他在呼叫 eat 時會不知
道要呼叫哪一個,則會以最先出現者
呼叫。
Python super() 函数
super() 函數是用來呼
叫父類的一個方法。

super() 是用來解決多
重繼承問題的,直接
用類別名稱呼叫父類
別方法在使用單一繼
承的時候沒問題。
執行後
方法覆寫 (Method
Overriding)
super 讓上下兩個都可以執

Problem 1: Design a class named Point2D to represent a point with x and y-
coordinates.
該類別包含:
1. 表示座標的私有資料欄位 x 和 y 。
2. 建構指定座標點的建構函數。
3. 分別針對資料欄位 x 和 y 的兩個 get 方法。
4. 名為 distance 的方法,返回該點到 (0,0) 的距離 Point2D 類型。
5. 每次輸入 N 是產生 N 個點的次數
6. 求 N 個點中距原點距離最大的點,並記錄它所產生的次數。
編寫一個測試程序,在定義的區域內產生 N 個 Point2D 物件的陣列
0.0 < x < 10.0 且 0.0 < y < 10.0 。 然後,程式找到具有最大和 分別到
原點(即座標為 (0, 0) 處的點)的最小距離。
說明

第一題:
1. 創建一個 class 其中包含:
1) 一個 __init__ ,裡面有初始中心點( 0,0 )的位置
2) 一個 def ,亂數產生點 x,y 的位置
3) 一個 def ,每次產生一個點記錄到 (0,0) 的距離最大為第幾個點跟
距離

然後下面執行輸入N個點產生亂數
Problem 2: Use the Account class practiced in the Lab to simulate an ATM machine.
Create
包含 ID 和編號的陣列中的帳戶,以及初始餘額 100 美元。 系統
提示使用者輸入 ID 。 一旦接受了 ID 和密碼,就會顯示主選單,
如範例運行所示。 您可以輸入選項 1 查看目前餘額, 2 提款, 3 存
款, 4 退出主選單。 一旦退出,系統將再次提示輸入 ID 。 因此,
系統一旦啟動,就不會停止。 。
說明:
1. 創建一個 class
2. def 一個 balance ,初始值 100 元,回傳裡面存

3. def 一個 withdrawing ,取出多少錢
4. def 一個 depositing ,存入錢
def 一個 exit ,中止程式
5.請根據模板中提示及下面說明完成
作業
說明:
1. 首先此 class 可以
記錄 ID 及密碼 ( 此在
init 中設定 )
2. 需要設定一個選擇
邏輯去決定要執行此
class 中的哪一個子 5. 此 class 中, deposit
def(1 查看目前餘 的 def ,是存入錢錢。
額, 2 提款, 3 存 此 def 中要完成執行此 def
款, 4 退出主選單 ) 要輸入一個值為存入錢錢
數。
3. 此 class
中, balance 6. 此 loop 會一直執行,所
的 def ,是用來查詢餘 以可以執行 1 去執
額 行, balance 去判定餘額。
4. 此 class
中, withdraw
9. 從此可以知道
的 def ,是用來取出 7. 此 loop 會一直執行,但 輸入新帳戶,會
錢。 如果輸入非 1-4 選項,將會 有新的餘額。
此 def 中要完成下列 : 選” error” ,並且繼續執
一 . 執行此 def 要輸入 行。
一個值為取出錢錢
二 . 當取出錢錢超過餘 8. 此 loop 會一直執行,但
額時,要顯示”餘額不 如果輸入” 4” 將會跳離這
足 !” 個帳戶,並請你重新輸入 ID
及 password
1. 延續上面,首先要能記
住原本 ID 及此 password
加分說明 : 下的餘額

確認餘額為結束前面
loop 後的餘額

2. 如果在此 ID 之下,輸入
的 password 於原本不
同,將顯示”你的密碼是錯
誤的”,
並且有三次機會。

3. 如果 3 次都輸入錯誤,
將顯示”請重新輸入 ID 及
密碼”,並且重新執行輸入
ID 及密碼階段。

You might also like