标签:get 属性 img getter 方便 set bsp 设置 调用
property
#property的作用:相当于把方法进行了封装, 开发者在对属性设置数据的时候更方便
class Dog(object): def __init__(self): self.__num = 100 def set_num(self,new_num): print("---setter") self.__num = new_num def get_num(self): print("----getter--") return self.__num num = property(get_num,set_num) #通过属性实现这种效果 dog1 = Dog() #print(dog1.get_num()) #dog1.set_num(50) #print(dog1.get_num()) print("-"*50) dog1.num = 111 #相当于调用了dog1.set_num(200) print(dog1.num) #相当于调用了dog1.get_num()
#### 运行结果 ---setter ----getter-- 111
#注意点: #t.num 到底是调用getNum()还是setNum(),要根据实际的场景来判断, #1. 如果是给t.num赋值 那么一定调用setNum() #2. 如果是获取t.num的值,那么就一定调用getNum()
@property
class Dog(object): def __init__(self): self.__num = 100 @property def to_num(self): #同名函数 print("---getter") return self.__num @to_num.setter #函数名.setter def to_num(self,new_num): #同名函数 print("---setter") self.__num = new_num # num = property(get_num,set_num) dog1 = Dog() dog1.to_num = 111 #相当于调用to_num(111) print(dog1.to_num) #相当于调用to_num()
---setter ---getter 111
标签:get 属性 img getter 方便 set bsp 设置 调用
原文地址:http://www.cnblogs.com/venicid/p/7922988.html