python property

from datetime import date, datetime
class User:
    def __init__(self, name, birthday):
        self.name = name
        self.birthday = birthday
        self._age = 0

    @property
    def age(self):
        return datetime.now().year - self.birthday.year

    @age.setter # 这里必须使用已经定义了的属性,才能使用setter
    def age(self, value):
        self._age = value

if __name__ == "__main__":
    user = User("bobby", date(year=1987, month=1, day=1))
    user.age = 30
    print(user._age)
    print(user.age)

 

posted @ 2019-08-11 17:12  下路派出所  阅读(169)  评论(0编辑  收藏  举报