python property() 函数用于返回 property 属性
通常用来 建立和管理 class attribute
class property(fget=None, fset=None, fdel=None, doc=None)
Return a property attribute.
fget is a function for getting an attribute value.
fset is a function for setting an attribute value.
fdel is a function for deleting an attribute value.
And doc creates a docstring for the attribute.
为一个类添加 property属性
class Person:
def __init__(self):
self._name = None
def get_name(self):
print('get_name called')
return self._name
def set_name(self, i):
print('set_name called')
self._name = i
def del_name(self):
print('del_name called')
del self._name
name = property(get_name, set_name, del_name, "Person's Name Attribute")
d = Person()
d.name = 'Pankaj'
print(d.name)
del d.name
'''
class Person:
def __init__(self):
self._name = None
def get_name(self):
print('get_name called')
return self._name
def set_name(self, i):
print('set_name called')
self._name = i
def del_name(self):
print('del_name called')
del self._name
name = property(get_name, set_name, del_name, "Person's Name Attribute")
d = Person()
d.name = 'Pankaj'
print(d.name)
del d.name
'''
注意: Person name property 是通过指定的方法管理的,实际属性为 Person 的私有属性 _name
我们可以建立 只读属性或者 non-deletable attribute。
# non-delete
name = property(get_name, set_name, None)
# read-only
name = property(get_name, None, None)
基于 装饰器,python 提供了 property 的简写
class Data:
def __init__(self):
self._id = None
@property
def id(self):
print('id getter')
return self._id
@id.setter
def id(self, i):
print('id setter')
self._id = i
@id.deleter
def id(self):
print('id deleter')
del self._id
d = Data()
d.id = 100
print(d.id)
del d.id