【Python】@property的用法
生活随笔
收集整理的這篇文章主要介紹了
【Python】@property的用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
設想我們要給一個student()類的一個實例s,添加一個score的屬性,比如:
s.score=999999
這個值明顯是不合理的,但是它卻是可行的,怎么能改變這種情況?我們能想到的就是用類方法
class student:
def setsore:
#code
?
def getsocre:
#code
這樣是可行的,但是沒有使用屬性直接設置方便,這時候就可以用到@property裝飾器了。
當使用@property裝飾器對getattr方法進行裝飾的時候,會自動產生一個對setattr方法
進行裝飾的裝飾器getattr.setattr ?這樣,就可以在實例中直接使用屬性對getattr和setattr方
法進行調用
例子:
1 class screen: 2 @property 3 def width(self): 4 return self._width 5 6 7 @width.setter #裝飾getwidth方法,即裝飾width方法產生的裝飾器 8 def width(self, width): #注意,在這里setwidth方法和getwidth方法名一樣 9 self._width = width 10 11 12 @property 13 def height(self): 14 return self._height 15 16 17 @height.setter 18 def height(self, h): 19 self._height = h 20 21 22 @property 23 def resolution(self): 24 return self._width * self._height 25 26 s = screen() 27 s.width = 1024 28 s.height = 768 29 print(s.resolution) 30 assert s.resolution == 786432, '1024 * 768 = %d ?' % s.resolution參考資料:廖雪峰的官方網站http://www.liaoxuefeng.com/
轉載于:https://www.cnblogs.com/fcyworld/p/6187431.html
總結
以上是生活随笔為你收集整理的【Python】@property的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 12-16php测试题
- 下一篇: python入门(1)python的前景