@property裝飾器作用:把一個方法變成屬性調用
使用@property可以實現將類方法轉換為只讀屬性,同時可以自定義setter、getter、deleter方法
@property&@.setter
class Person(object): @property def birth(self): return self._birth @birth.setter def birth(self,value): self._birth=value if __name__ == '__main__': p=Person() p.birth=1985 print(p.birth) ---------------運行結果----------------- 1985
把方法變成屬性,只需要在方法前添加@property裝飾器即可。
繼續添加一個裝飾器@birth.setter,給屬性賦值
@.getter
上例中因為在birth方法中返回了birth值,所以即使不調用getter方法也可以獲得屬性值。接下來再將函數稍作修改,看下getter方法是怎么使用的。
class Person(object): @property def birth(self): return 'my birthday is a secret!' @birth.setter def birth(self,value): self._birth=value if __name__ == '__main__': p=Person() p.birth=1985 print(p.birth) ------------------運行結果------------------ my birthday is a secret!
因為將birth方法的返回值寫了固定值,所以即使賦值成功,但是並不會打印。
如果想打印出具體的值,可以增加getter方法。
class Person(object): @property def birth(self): return self._birth @birth.setter def birth(self,value): self._birth=value @birth.getter def birth(self): return self._birth if __name__ == '__main__': p=Person() p.birth=1985 print(p.birth) ------------------運行結果------------------- 1985
@.deleter
@property含有一個刪除屬性的方法
class Person(object): @property def birth(self): return self._birth @birth.setter def birth(self,value): self._birth=value @birth.getter def birth(self): return self._birth @birth.deleter def birth(self): del self._birth if __name__ == '__main__': p=Person() p.birth=1985 print(p.birth) del p.birth print(p.birth) ---------------運行結果----------------- 1985 #刪除birth屬性后,再次訪問會報錯 AttributeError: 'Person' object has no attribute '_birth'