@property
@property
修飾器,可以讓原本的 method 變成變數(屬性)的形式class M:
def __init__(self):
self.__val = 5
@property
def a(self):
return (self.__val + 5)
c = M()
print(c.a)
# 10
# c.a = 20
# 跳錯,不可變更
# AttributeError: can't set attribute
class M:
def __init__(self):
self._val = 10
@property
def a(self):
return (self._val + 5)
@a.setter
def a(self, n):
if n < 0:
self._val = 0
else:
self._val = n
@a.deleter
def a(self):
del self._val
print("del val")
c = M()
print(c._val)
# 10
# setter
c.a = -10
print(c._val)
# 0 因 < 0
# getter 直接使用
print(c.a)
# 5 因 0+5
# deleter
del c.a
# del val
print(c.a)
# self._val 已經被刪除
# AttributeError: 'M' object has no attribute '_val'
來看看繼承的部分