Python內置的@property
裝飾器是負責把一個方法變成屬性調用的python
class Stu(object): def __init__(self,age): self.__age=age @property #直接調用屬性 def birth(self): return self._age @birth.setter #設置屬性 def birth(self, value): self.__age = value @birth.deleter #刪除屬性 def birth(self): del self.__age #調用方法爲 stu_a = Stu(3) stu_a.birth # >>> 3 調用@property修飾的方法 stu_a.birth = 4 >>> 調用@setter修飾的方法 del stu_a.birth >>調用@deleter修飾的方法
事實上property是一個類,裏面封裝了property,setter,deleter等方法,其中__init__()構造函數中,是存在4個參數的!函數
def __init__(self, fget=None, fset=None, fdel=None, doc=None): pass
這也就是property的另外一種用法:property()spa
class Stu(object): def __init__(self,age): self.__age=age def get_age(self): return self._age def set_age(self, value): self.__age = value def del_age(self): del self.__age gsd = property(get_age, set_age, del_age) stu1 = Stu(1) #調用方式: stu1.gsd stu1.gsd = 2 del stu1.gsd
@property其實就是經過描述符來定製,雖然內置方法爲c封裝的,但能夠用python代碼簡單的實現@property的功能:code
class B: # property對象 def __init__(self, a): # 這裏傳入的是aa方法 self.a = func def __get__(self, instance, owner): ret = self.func(instance) # instance爲A的實例對象,即aa()函數須要的self return ret class A: @B # B = B(aa) def aa(self): return "property" b = A() print(b.aa)