python @property
时间: 2024-01-26 18:03:51 浏览: 70
Python 中@property的用法详解
5星 · 资源好评率100%
The @property decorator in Python is used to define a method as a property, which allows us to access it like an attribute without calling it as a method. It is a convenient way to implement getter and setter methods for a class attribute.
For example, consider a class that has a private attribute called "age". We can define getter and setter methods for this attribute using the @property decorator as follows:
class Person:
def __init__(self, name, age):
self.name = name
self._age = age
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if value < 0:
raise ValueError("Age cannot be negative")
self._age = value
Here, we have defined a getter method for the "age" attribute using the @property decorator. This allows us to access the age attribute like an attribute, without calling it as a method:
person = Person("John", 25)
print(person.age) # 25
We have also defined a setter method for the "age" attribute using the @age.setter decorator. This allows us to set the age attribute like an attribute, without calling it as a method:
person.age = 30
print(person.age) # 30
If we try to set a negative value for the "age" attribute, it will raise a ValueError:
person.age = -1
# ValueError: Age cannot be negative
阅读全文