标签:use now() 属性 pytho code prope coding col turn
Python中有一个被称为属性函数(property)的小概念
1 #!/user/bin/env python 2 # -*- coding:utf-8 -*- 3 from datetime import date, datetime 4 5 6 class User: 7 def __init__(self, name, birthday): 8 self.name = name 9 self.birthday = birthday 10 self._age = 0 11 12 def get_age(self): 13 return datetime.now().year - self.birthday.year 14 15 @property 16 def age(self): 17 return datetime.now().year - self.birthday.year 18 19 @age.setter 20 def age(self, value): 21 self._age = value 22 23 24 # 这里使用 __name__ = ‘__main__‘ 条件判断是为了,在其他模块中引用的时候,不会执行测试代码 25 if __name__ == ‘__main__‘: 26 user = User(‘zy‘, date(year=1998, month=6, day=8)) 27 user.age = 30 28 print(user._age) 29 print(user.age) 30 print(user.get_age())
30 21 21
标签:use now() 属性 pytho code prope coding col turn
原文地址:https://www.cnblogs.com/zydeboke/p/11259003.html