使用 Python3 進行物件導向程式設計(1)

使用 Python3 進行物件導向程式設計(1)

簡介

物件導向程式設計(Object-oriented programming, OOP)是一種具有物件概念的程式編程典範(programming paradigm)[1]。

OOP 透過把系統視為由許多彼此互動的物件所組成,使用OO技術所設計的系統一般來說可提高可了解性可修改性

舉一個例子,我們可以將一家公司的人員建模(modeling) 成為一個 Person 的物件,一個 Person 可以有‘ID’, ‘Name’, ‘Address’, ‘Salary’ 等屬性;另外還可能有 ‘Raise_Salary’ (調薪) 的動作,會去更改底薪的數值。

類別(Class)與物件(Object)

在OOP中,我們會用 Class 來為同一類的事物建立一個共通的資料結構(另外還有伴隨著這個事物的行為或方法),接下來我們用一個貓咪的例子作為本系列文章的範例。

比如,針對每一個貓咪,我們想要記錄牠的名字(Name)、年紀(Age)、顏色。在 Python 中,我們會用 ‘class’ 這個關鍵字來定義一個類別(class)。

class Cat:
    # Initializer / Instance Attributes
    def __init__(self, name, age, color):
        self.name = name
        self.age = age
        self.color = color

上列程式中 __init__() 是在建立一個 Cat 物件時,會自動被呼叫用來設定 Cat物件的 name, age, color 等屬性變數(Instance Attributes) 的建構函式。

以上的程式只是定義了貓的資料,要建立一個實際 Cat 物件時(也叫做實例化)要用 Cat(‘Kitty’,1,’white’) 這樣的語法來建立一個Cat的物件(object, 或是 instance),它的 name 會被設定成 ‘Kitty’, age 會被設定成 1, color 會被設定成 ‘white’

class Cat:
    # Initializer / Instance Attributes
    def __init__(self, name, age, color):
        self.name = name
        self.age = age
        self.color = color

# 實例化 Cat 物件
kitty = Cat("Kitty", 1, "white")
print("type of kitty is {}".format(type(kitty)))
annie = Cat("Annie", 3, "gold")
print("type of annie is {}".format(type(annie)))
print("Is kitty equal to annie: {}".format(kitty==annie))

# 讀取物件的的屬性變數(Instance Attributes) 
print("{} is {} and {} is {}.".format(
kitty.name, kitty.color, annie.name, annie.color))

如果將以上的程式碼儲存成 cat_class.py,並在 terminal 中執行,會出現以下的結果

$ python cat_class.py
type of kitty is <class '__main__.Cat'>
type of annie is <class '__main__.Cat'>
Is kitty equal to annie: False
Kitty is white and Annie is gold.

從以上的執行結果可以知道 kitty, annie 都是 Cat 這個 class(類別),但二者的值是不相同的,代表是二個不同的物件(object)

練習

假設有五隻貓 Cat(“Kitty”, 1, “white”), Cat(“Annie”, 3, “gold”), Cat(“Elsa”, 5, “gold”), Cat(“Kiki”, 7, “black”), Cat(“Lily”, 4, “white”),如何寫一個程式找出貓咪最大的年紀數目?

class Cat:
    # Initializer / Instance Attributes
    def __init__(self, name, age, color):
        self.name = name
        self.age = age
        self.color = color

# 建立五隻貓咪並儲存在 List 之中
cats = [Cat("Kitty", 1, "white"),
        Cat("Annie", 3, "gold"),
        Cat("Elsa", 5, "gold"),
        Cat("Kiki", 7, "black"),
        Cat("Lily", 4, "white")]
# 找出最大的年紀數字
print("The largest age number is {}".format(max([x.age for x in cats])))

[1] wikipedia:物件導向程式設計

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料