類別中每個屬性都要有初始值,就算這個值是0或空字串都可以,例如在設定預設值時,在__init__方法中指定這初始值是允許的,如果對某個屬性進行了這樣的設定,就無需放入對此屬性提供初始值的參數
範例如下 :
class Car():
def __init__(self,year,brand,color):
self.year = year
self.brand = brand
self.color = color
self.miles = 0 # 建立一個miles屬性初始值為0
def get_mile(self): # 定義一個get_mile方法可以存取miles
print("Your "+self.brand+" has "+str(self.miles)+" miles on it")
car1 = Car(10,"toyota","black") # 建立一個car1實例
car1.get_mile() # 用實例呼叫get_mile方法
輸出結果 :
Your toyota has 0 miles on it
想要修改屬性的值最簡單的方法是透過實例直接存取
範例如下 :
class Car():
def __init__(self,year,brand,color):
self.year = year
self.brand = brand
self.color = color
self.miles = 0
def get_mile(self):
print("Your "+self.brand+" has "+str(self.miles)+" miles on it")
car1 = Car(10,"toyota","black")
car1.miles = 87 # 使用據點標示法來直接存取並設定出仔的miles屬性
car1.get_mile() # 在car1實例中找出miles屬性並將87指定進去
輸出結果 :
Your toyota has 87 miles on it
我們可以直接將值傳入方法中,讓它在內部進行更新修改,這樣我們就不需要直接存取屬性
範例如下 :
class Car():
def __init__(self,year,brand,color):
self.year = year
self.brand = brand
self.color = color
self.miles = 0
def get_mile(self):
print("Your "+self.brand+" has "+str(self.miles)+" miles on it")
# 新增一個update_mile方法來接收里程數值(就是mileage),然後再存到self.miles裡
def update_mile(self,mileage):
self.miles = mileage
car1 = Car(10,"toyota","black")
car1.update_mile(87) # 呼叫update_mile方法並將87當作引數傳入mileage參數中
car1.get_mile()
輸出結果 :
Your toyota has 87 miles on it
有時候我們會希望讓屬性以特定的數值增加,而不是新增新的值進去,我們可以再創一個增加值的方法來呼叫它
範例如下 :
class Car():
def __init__(self,year,brand,color):
self.year = year
self.brand = brand
self.color = color
self.miles = 0
def get_mile(self): # 取得公里數
print("Your "+self.brand+" has "+str(self.miles)+" miles on it")
def update_mile(self,mileage): # 更新公里數
self.miles = mileage
def add_mile(self,kilometer): # 增加公里數
self.miles += kilometer # 接收一個kilometer值加到self.miles裡
car1=Car(10,"toyota","black")
car1.update_mile(87)
car1.get_mile()
car1.add_mile(9400) # 呼叫add_mile方法並傳入9400
car1.get_mile()
輸出結果 :
Your toyota has 87 miles on it
Your toyota has 9487 miles on it
附上排版較精美的
HackMD網址:https://hackmd.io/55aNlgeQS8G-lR9s2XLbVg?view
資料來源:<<python程式設計的樂趣>>-Eric Matthes著/H&C譯