Mike的Python學院

軟體程式設計、Python、物件導向程式設計、OOP、軟體開發、程式語言

Mike Ku

Learn Code With Mike品牌創辦人

2021/10/20

3個必須瞭解的Python屬性觀念

Q:什麼是實體屬性(Instance Attribute)?
需伴隨物件(Object)的生成來建立,也就是透過點(.)的語法或在建構式(Constructor)中所生成的屬性(Attribute)。各物件(Object)的實體屬性(Instance Attribute)各自獨立,修改某一個物件(Object)的實體屬性(Instance Attribute)值時,不會影響到其他物件。如下範例:
class Cars:
pass
mazda = Cars()
mazda.color = "blue"
toyota = Cars()
toyota.color = "red"
print("mazda color: ", mazda.color)
print("toyota color: ", toyota.color)
接下來我們來看透過建構式(Constructor)所建立的屬性(Attribute):
class Cars:
# 建構式
def __init__(self, color, seat):
self.color = color
self.seat = seat
self.weight = 140
mazda = Cars("blue", 4)
mazda.color = "yellow"
mazda.seat = 8
mazda.weight = 200
print("mazda color: ", mazda.color)
print("mazda seat: ", mazda.seat)
print("mazda weight: ", mazda.weight)
Q:什麼是類別屬性(Class Attribute)?
定義在類別層級的屬性(Attribute),也就是在建構式(Constructor)之外的屬性(Attribute)。可以不需要建立物件(Object),直接透過類別名稱存取。各物件共享類別屬性(Class Attribute)值,也就是說當我們修改類別屬性(Class Attribute)值時,每一個透過此類別(Class)所建立的物件(Object),都會受到影響。如下範例:
class Cars:
door = 4
# 建構式
def __init__(self, color, seat):
self.color = color
self.seat = seat
self.weight = 140
mazda = Cars("blue", 4)
print("mazda original door: ", mazda.door)
Cars.door = 6
print("mazda new door: ", mazda.door)
Q:什麼是屬性(Property)?
是一個允許我們設定及取得屬性(Attribute)值的物件(Object),當我們想要對類別(Class)中的屬性(Attribute)有更多的控制時,就會使用Python的屬性(Property)來達成。如下範例:
class Cars:
# 建構式
def __init__(self, weight):
self.weight = weight
@property
def weight(self):
return self.__weight
@weight.setter
def weight(self, value):
if value <= 0:
raise ValueError("Car weight cannot be 0 or less.")
self.__weight = value
在讀取屬性(Attribute)的方法上方加上@property Decorator,並且將方法名稱修改為weight,這個weight就是屬性(Property)。接著在設定屬性(Attribute)的方法上方加上@property.setter,也就是@weight.setter,意思就是告訴類別(Class)當來源端要設定屬性(Property)值時,要呼叫這個方法(Method)。
如果想要學習更多的Python應用教學,歡迎前往Learn Code With Mike( https://www.learncodewithmike.com/2020/01/python-attribute.html )網站觀看更多精彩內容。
2 0 242 0