測試環境為 CentOS 8 x86_64 (虛擬機)
使用 Property 時可以把 類別(Class) 的 方法 (Method) 轉變成存取 屬性 (Attribute) 包含 setter , getter 與 deleter 等方法 (Method) , 參考文章 – https://www.maxlist.xyz/2019/12/25/python-property/
使用 Property 時屬性 (Attribute) 通常使用 __attribute ( __double_leading_underscore ) 這種命名規則 ( 請參考 – https://benjr.tw/104282 ) 是不希望它被直接存取.
[root@localhost ~]# vi computer.py class computer: def __init__(self): self.__CPU = 'Intel' customer1 = computer() print(customer1.CPU)
執行結果
[root@localhost ~]# python3 computer.py Traceback (most recent call last): File "computer.py", line 6, in <module> print(customer1.CPU) AttributeError: 'computer' object has no attribute 'CPU'
__attribute 屬性 (Attribute) 存取需透過 @Property 包含 setter , getter 與 deleter 等方法 (Method) 來存取.
- 範例: @Property 的使用與 getter.
[root@localhost ~]# vi computer1.py class computer: def __init__(self): self.__CPU = 'Intel' @property def CPU(self): return self.__CPU customer1 = computer() print(customer1.CPU) customer1.CPU = 'AMD'
執行結果
[root@localhost ~]# python3 computer1.py Intel Traceback (most recent call last): File "computer1.py", line 11, in <module> customer1.CPU = 'AMD' AttributeError: can't set attribute
說明:
定義 computer 類別與初始化方法.class computer: def __init__(self): self.__CPU = 'Intel'
並透過 @Property 把 CPU 類別(Class) 的 方法 (Method) 轉變成可讀取 __CPU 屬性 (Attribute) .
@property def CPU(self): return self.__CPU
建立 customer1 instance
customer1 = computer()
當讀取 Instance 的 CPU 屬性 customer1.CPU 時 是呼叫 CPU 方法(Method – def CPU(self) ),這方法為 CPU 屬性的 getter.
print(customer1.CPU)
執行結果
Intel
當我們要改變 Instance 的 CPU 屬性時卻生錯誤了,這是因為我們沒有定義 CPU 屬性相對應的 setter 才會出現錯誤.
customer1.CPU = 'AMD'
執行結果
Traceback (most recent call last): File "computer1.py", line 11, in <module> customer1.CPU = 'AMD' AttributeError: can't set attribute
- 範例: 增加 Property 的 setter 與 deleter
[root@localhost ~]# vi computer2.py class computer: def __init__(self): self.__CPU = 'Intel' @property def CPU(self): return self.__CPU @CPU.setter def CPU(self, value): self.__CPU = value @CPU.deleter def CPU(self): del self.__CPU print('del complete') customer1 = computer() print(customer1.CPU) customer1.CPU = 'AMD' print(customer1.CPU) del customer1.CPU
執行結果
[root@localhost ~]# python3 computer2.py Intel AMD del complete
說明:
- getter
執行print(customer1.CPU)
呼叫
@property def CPU(self): return self.__CPU
結果
Intel
- setter
執行 settercustomer1.CPU = 'AMD'
呼叫
@CPU.setter def CPU(self, value): self.__CPU = value
執行 getter
print(customer1.CPU)
呼叫
@property def CPU(self): return self.__CPU
執行結果
AMD
- deleter
執行del customer1.CPU
呼叫
@CPU.deleter def CPU(self): del self.__CPU print('del complete')
執行結果
del complete
- getter