python属性
Python property() function returns a property attribute. It’s mostly used to create a manageable class attribute.
Python property()函数返回一个property属性。 它主要用于创建可管理的类属性。
Python属性() (Python property())
Python property() function syntax is:
Python property()函数语法为:
class property(fget=None, fset=None, fdel=None, doc=None)
- fget: function for getting the attribute value fget :获取属性值的函数
- fset: function to set the attribute value fset :用于设置属性值的函数
- fdel: function to delete the attribute fdel :删除属性的功能
- doc: creates the docstring for the attribute to be used in help() function. doc :为将在help()函数中使用的属性创建docstring。
Let’s look at an example to create property attribute in a class.
让我们看一个在类中创建属性属性的示例。
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
Output:
输出:
set_name called
get_name called
Pankaj
del_name called
Notice that Person name property is managed through specified methods and it’s using the _name
private property of Person.
注意,Person名称属性是通过指定的方法进行管理的,并且使用了Person的_name
私有属性。
We can create a read-only attribute or non-deletable attribute using property function.
我们可以使用属性函数创建只读属性或不可删除属性。
If we define property function as:
如果我们将属性函数定义为:
name = property(get_name, set_name, None)
Then del d.name
will throw exception as AttributeError: can't delete attribute
.
然后del d.name
将抛出异常,因为AttributeError: can't delete attribute
。
Similarly, if we define property attribute as:
同样,如果我们将property属性定义为:
name = property(get_name, None, None)
The name will be read-only. If we try to set its value using d.name = 'Pankaj'
then exception will be thrown as AttributeError: can't set attribute
.
该名称将是只读的。 如果我们尝试使用d.name = 'Pankaj'
设置其值, d.name = 'Pankaj'
异常AttributeError: can't set attribute
。
Python属性装饰器 (Python Property Decorator)
We can use @property decorator to achieve the same thing.
我们可以使用@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
Output:
输出:
id setter
id getter
100
id deleter
Reference: Official Documentation
参考: 官方文档
python属性