1. 程式人生 > >python學習手冊(第4版) 第三十七章 管理屬性

python學習手冊(第4版) 第三十七章 管理屬性

1.property內建函式

把結果賦值給一個類屬性來建立一個特性

>>> class Person: ...     def __init__(self,name): ...         self._name = name ...     def getName(self): ...         print('fetch...') ...         return self._name ...     def setName(self,value): ...         print('change...') ...         self._name = value ...     def delName(self): ...         print('remove...') ...         del self._name ...     name = property(getName,setName,delName,'name property docs')           # 使用property內建函式 ... >>> bob = Person('Bob Smith') >>> print(bob.name)                                  # 呼叫了getName方法 fetch... Bob Smith >>> bob.name = 'Robert Smith'                  # 呼叫了setName方法 change... >>> del bob.name                                       # 呼叫了delName方法 remove... >>> >>> sue = Person('Sue Jones')                  # 可以多次建立例項 >>> print(sue.name) fetch... Sue Jones >>> print(Person.name.__doc__)              # 調出自定義的文件說明 name property docs >>>

>>> class Othre(Person):                          # property特性可以被繼承 ...     pass ... >>> Jim = Othre('Jim San') >>> Jim.name fetch... 'Jim San' >>>

2.裝飾器的兩種寫法

寫法一:

@decorator

def func(args):pass

寫法二:

def func(args):pass

func = decorator(func)

而property可以作為裝飾器使用,所以有兩種寫法,

class Person():

    @property

    def name(self):

        pass

class Person():

    def name(self):

        pass

    name = property(name)

3.官方介紹property

>>> help(property) Help on class property in module builtins:

class property(object)  |  property(fget=None, fset=None, fdel=None, doc=None) -> property attribute        # 對應三種操作,讀/寫/刪,還可自定義文件  |  |  fget is a function to be used for getting an attribute value, and likewise  |  fset is a function for setting, and fdel a function for del'ing, an  |  attribute.  Typical use is to define a managed attribute x:  |  |  class C(object):                         |      def getx(self): return self._x  |      def setx(self, value): self._x = value  |      def delx(self): del self._x  |      x = property(getx, setx, delx, "I'm the 'x' property.")                                  # 寫法一  |  |  Decorators make defining new properties or modifying existing ones easy:  |  |  class C(object):  |      @property                                                                                                # 寫法二  |      def x(self):  |          "I am the 'x' property."  |          return self._x  |      @x.setter  |      def x(self, value):  |          self._x = value  |      @x.deleter  |      def x(self):  |          del self._x

注意:

property內建函式只是建立一個特定型別的描述符的一種簡化方法,而這種描述符在屬性訪問時執行方法函式。

從功能上講,描述符協議允許我們把一個特定屬性的get和set操作指向我們提供的一個單獨類物件的方法,從而實現屬性攔截。

實際上,property內建函式使類物件中預設呼叫了__getattr__  __setattr__  __delattr__操作符過載的方法,從而重定義屬性方法。