[7.1] property dynamic property

 Python, the concept is called a small function property (Property) of

  • The method of converting the read-only attribute class
  • Re-implement a property setter and getter methods
 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 is  
. 19      @ age.setter
 20 is      DEF Age (Self, value):
 21 is          self._age = value
 22 is  
23 is  
24  # used herein __name__ = '__main__' conditional order, when referring to the other modules, not executed test code 
25  IF  the __name__ == ' __main__ ' :
 26 is      User = the User ( ' ZY ' , DATE (= 1998 year, month the =. 6, =. 8 Day ))
 27      user.age = 30
 28      Print (user._age)
29     print(user.age)
30     print(user.get_age())
30
21
21

  

Guess you like

Origin www.cnblogs.com/zydeboke/p/11259003.html