python property
时间: 2023-09-11 15:05:00 浏览: 52
In Python, a property is a special attribute that allows us to define getter, setter, and deleter methods for a class attribute. It provides a way to encapsulate the access to an attribute, allowing us to control its value and behavior.
The property() function is used to create a property object. It takes up to three arguments:
- fget: the getter method for the property
- fset: the setter method for the property
- fdel: the deleter method for the property
Here's an example of how to use the property() function:
```
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@name.deleter
def name(self):
del self._name
p = Person("John")
print(p.name) # Output: John
p.name = "Doe"
print(p.name) # Output: Doe
del p.name
print(p.name) # Output: AttributeError: 'Person' object has no attribute '_name'
```
In this example, we defined a Person class with a name attribute. By using the @property decorator, we defined a getter method that returns the value of the name attribute. We also defined a @name.setter decorator that allows us to set the value of the name attribute. Finally, we defined a @name.deleter decorator that allows us to delete the name attribute.