python property() 函数用于返回 property 属性
    通常用来 建立和管理 class attribute

    1. class property(fget=None, fset=None, fdel=None, doc=None)
    2. Return a property attribute.
    3. fget is a function for getting an attribute value.
    4. fset is a function for setting an attribute value.
    5. fdel is a function for deleting an attribute value.
    6. And doc creates a docstring for the attribute.

    为一个类添加 property属性

    1. class Person:
    2. def __init__(self):
    3. self._name = None
    4. def get_name(self):
    5. print('get_name called')
    6. return self._name
    7. def set_name(self, i):
    8. print('set_name called')
    9. self._name = i
    10. def del_name(self):
    11. print('del_name called')
    12. del self._name
    13. name = property(get_name, set_name, del_name, "Person's Name Attribute")
    14. d = Person()
    15. d.name = 'Pankaj'
    16. print(d.name)
    17. del d.name
    18. '''
    19. class Person:
    20. def __init__(self):
    21. self._name = None
    22. def get_name(self):
    23. print('get_name called')
    24. return self._name
    25. def set_name(self, i):
    26. print('set_name called')
    27. self._name = i
    28. def del_name(self):
    29. print('del_name called')
    30. del self._name
    31. name = property(get_name, set_name, del_name, "Person's Name Attribute")
    32. d = Person()
    33. d.name = 'Pankaj'
    34. print(d.name)
    35. del d.name
    36. '''

    注意: Person name property 是通过指定的方法管理的,实际属性为 Person 的私有属性 _name
    我们可以建立 只读属性或者 non-deletable attribute。

    1. # non-delete
    2. name = property(get_name, set_name, None)
    3. # read-only
    4. name = property(get_name, None, None)

    基于 装饰器,python 提供了 property 的简写

    1. class Data:
    2. def __init__(self):
    3. self._id = None
    4. @property
    5. def id(self):
    6. print('id getter')
    7. return self._id
    8. @id.setter
    9. def id(self, i):
    10. print('id setter')
    11. self._id = i
    12. @id.deleter
    13. def id(self):
    14. print('id deleter')
    15. del self._id
    16. d = Data()
    17. d.id = 100
    18. print(d.id)
    19. del d.id