Python中@property的使用講解

裝飾器(decorator)可以給函數(shù)動態(tài)加上功能,對于類的方法,裝飾器一樣起作用。Python內(nèi)置的@property裝飾器就是負(fù)責(zé)把一個方法變成屬性調(diào)用的:


下面寫一個例子,如有不懂的同學(xué)可以聯(lián)系我郵箱

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__='byx54192@gmail.com'

class Student(object):

    @property #將birth 轉(zhuǎn)換為屬性,外部可是直接s.birth訪問
    def birth(self):
        return self._birth

    @birth.setter #@property本身又創(chuàng)建了另一個裝飾器@score.setter,負(fù)責(zé)把一個setter方法變成屬性賦值
    def birth(self, value):
        if value>0 and value<100:
            self._birth = value
        else:
            raise ValueError('birth must between 0~100')

    @property #將age方法轉(zhuǎn)換為屬性,外部調(diào)用時,可以用s.age訪問。
    def age(self):
        return 2015 - self._birth
s= Student()
s.birth=10
print(s.age)
print(s.birth)

練習(xí)

請利用@property給一個Screen對象加上width和height屬性,以及一個只讀屬性resolution:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__='byx54192@gmail.com'

class Screen(object):
    @property
    def width(self):
        return self._width
    @width.setter
    def width(self,value):
        if value!=768:
            return 0
        self._width=value

    @property    
    def height(self):
        return self._height
    @height.setter
    def height(self,value):
        if value!=1024:
            return 0
        self._height=value

    @property
    def resolution(self):
        return self._width*self._height
s=Screen()
s.width=768
s.height=1024
print('resolution=',s.resolution)
if s.resolution == 786432:
    print('測試通過!')
else:
    print('測試失敗!')
圖片發(fā)自簡書App
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容