接下來會編寫一個代表小狗的簡單 Dog 類別,此類別代表的是任意一隻小狗,並不是只針對某一特定的小狗。 思考一下大多數的寵物狗具有什麼特性?有名字和年齡(資訊),還會蹲下和翻滾(行為), 在 Dog 類別中都放入這些資訊和行為。此類別會讓 Python 知道如何建立代表小狗的物件。 這個類別後,將會使用它建立代表特定小狗的實例。
建立 Dog 類別
以 Dog 類別所建立的每個實例都會存放有名字( name )和年齡( age ), 也讓每隻小狗有蹲下( sit() )和翻滾( roll_over() )的行為能力:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classDog(): """A simple attempt to model a dog."""
def__init__(self, name, age): """Initialize name and age attributes.""" self.name = name self.age = age
defsit(self): """Simulate a dog sitting in response to a command.""" print(self.name.title() + " is now sitting")
defroll_over(self): """Simulate rolling over in response to a command.""" print(self.name.title() + " rolled over!")
先定義一個 Dog 的類別,在 Python 中,第一個字母為大寫是類別的命名慣例。 這個類別定義的括號中是空的,因為我們要從零開始來建立這個類別。
__init__ 方法
屬於類別的函式稱為方法(method),之前學習函式的一切都適用於這裡所提到的「方法」,唯一最不同的就是呼叫方法的方式。 __init__方法是一種特殊的方法,每次當我們以 Dog 類別為基礎建立新的實例時, Python 都會自動執行這個方法。 這個方法的名字在開頭跟結尾都有兩個底線,這樣的命名慣例可防止 Python 的預設方法名稱與您建立的方法名稱發生衝突。
定義__init__方法有三個參數:self、name 和 age 。在此方法的定義中, self 是必要的,必須放在其它參數的前面。 self 必須放在定義中,因為當 Python 隨後呼叫這個__init__方法時,方法的呼叫會自動傳入 self 引數。 當建立 Dog 實例時, Python 會呼叫 Dog 類別的 __init__ 方法。 我們會把 name 和 age 當成引數傳入 Dog() ,而 self 則會自動傳入,因此不需要由我們傳入。 每當以 Dog 類別為基礎建立實例時,只需要提供 name 和 age 兩個引數值就可以了。
在__init__方法下內縮的程式區塊內,兩個變數都名字前面都有個 self 開頭, 以 self 為前導的變數都能提供類別中所有方法使用,還可透過任何由類別所建立的實例來存取這些變數。 self.name = name 會取得 name 參數中的值,並存放到 name 變數中,該變數會連接目前所建立的實例。 self.age = age 這行的處理過程跟 self.name = name 相同。 可由實例來存取的數就稱為屬性( attribute )。
Dog 類別中有定義兩個方法:sit() 和 roll_over()。 因為這兩個方法不需要額外的資訊,所以只定義一個 self 參數即可。之後建立的實例將可存取這兩個方法。
從類別建立實例
可以將類別想像成一組指令,指示如何建立實例的指令。 Dog 類別就是一系列的指令,讓 Python 知道如何建立代表某隻小狗的個別實例:
classCar(): """A simple attempt to represent a car."""
def__init__(self, make, model, year): """Initialize attributes to describe a car.""" self.make = make self.model = model self.year = year self.odometer_reading = 0
classCar(): """A simple attempt to represent a car."""
def__init__(self, make, model, year): """Initialize attributes to describe a car.""" self.make = make self.model = model self.year = year self.odometer_reading = 0
classCar(): """A simple attempt to represent a car."""
def__init__(self, make, model, year): """Initialize attributes to describe a car.""" self.make = make self.model = model self.year = year self.odometer_reading = 0
classCar(): """A simple attempt to represent a car."""
def__init__(self, make, model, year): """Initialize attributes to describe a car.""" self.make = make self.model = model self.year = year self.odometer_reading = 0
defread_odometer(self): """Print a statement showing the car's mileage.""" print("This car has " + str(self.odometer_reading) + " miles on it.")
defupdate_odometer(self, mileage): """ Set the odometer reading to the given value. Reject the change if it attempts to roll the odometer back. """ if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!")
classCar(): """A simple attempt to represent a car."""
def__init__(self, make, model, year): """Initialize attributes to describe a car.""" self.make = make self.model = model self.year = year self.odometer_reading = 0
defread_odometer(self): """Print a statement showing the car's mileage.""" print("This car has " + str(self.odometer_reading) + " miles on it.")
defupdate_odometer(self, mileage): """ Set the odometer reading to the given value. Reject the change if it attempts to roll the odometer back. """ if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!")
defincrement_odometer(self, miles): """Add the given amount to the odometer reading.""" self.odometer_reading += miles