一、property类
1 class Person(): 2 def __init__(self, name): 3 self.set_name(name) 4 5 def get_name(self): 6 return self.__name 7 8 def set_name(self, name): 9 self.__name = name 10 11 name = property(get_name, set_name) 12 13 p = Person('xiaoliu') 14 print(p.name) 15 p.name = 'banana' 16 print(p.name)
二、property修饰器
1 class Person(): 2 def __init__(self, name): 3 self.name = name 4 5 @property 6 def name(self): 7 return self.__name 8 9 @name.setter 10 def name(self, name): 11 self.__name = name 12 13 p = Person('xiaoliu') 14 print(p.name) 15 p.name = 'banana' 16 print(p.name)