@property
一、@property
- @property 是一个装饰器(decorator),它可以将一个方法转换为属性访问。在 Python 中,属性访问通常使用点运算符(.)来访问对象的属性,但有时我们
希望将某个方法的访问方式与属性一样
,这时就可以使用@property装饰器
。- 当我们
将一个方法使用 @property 装饰器修饰后,该方法就可以像访问属性一样通过属性名直接访问,而不需要使用方法调用的括号
。
二、代码
from datetime import datetime
class Person:
def __init__(self, name, birth_year):
self.name = name
self.birth_year = birth_year
@property
def age(self):
current_year = datetime.now().year
return current_year - self.birth_year
person = Person("Alice", 1990)
print(person.age)# 3 # 直接通过属性名访问年龄,而不是调用方法