@property 裝飾器

property() 函數做用於新式類,返回屬性值。html

class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        print('get')
        return self._x

    def setx(self, value):
        print('set')
        self._x = value

    def delx(self):
        print('del')
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")


# c = C()
# c.x = 12
# print(c.x)
# del c.x

 

@property 裝飾器用的最多。把一個方法變成屬性調用,那麼咱們在對實例屬性操做的時候,就知道該屬性極可能不是直接暴露的,而是經過getter和setter方法來實現的。python

# @property 裝飾器負責把一個方法變成屬性調用

class Student(object):
    # 把一個getter方法變成屬性,只需加上 @property
    @property
    def score(self):
        return self._score

    # 把一個setter方法變成屬性,@fun.setter
    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an interger!')
        if value < 0 or value > 100:
            raise  ValueError('score must between 0~100')
        self._score = value

s = Student()
s.score = 60
print(s.score)

 

class Parrot(object):
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

    # setter,deleter,這些額外函數名和property相同
    @voltage.setter
    def voltage(self, value):
        self._voltage = value

    @voltage.deleter
    def voltage(self):
        del self._voltage

 

參考:
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143186781871161bc8d6497004764b398401a401d4cce000
http://www.runoob.com/python/python-func-property.html函數

相關文章
相關標籤/搜索