Python property动态属性


from datetime import datetime, date


class User:
    def __init__(self, name, birthday):
        self.name = name
        self.birthday = birthday
        self._age = 0

    # def get_age(self):
    #     return datetime.now().year - self.birthday.year

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

    @age.setter
    def age(self, value):
        self._age = value


if __name__ == "__main__":
    user = User("tom", date(year=1987, month=11, day=9))
    user.age = 32  # 可以通过这种方式来读写类中的私有属性
    print(user._age)


posted @ 2019-03-21 23:17  不将就!  阅读(206)  评论(0编辑  收藏  举报