property是一个装饰器,可以在类中装饰在函数上,主要作用是对类中的添加,删除,更改做隐藏操作
原先操控添加,删除,更改一个被封装的属性
class EGG:
__count=0
def get_count(self):
return self.__count
def set_count(self,num):
self.__count=num
def del_count(self):
del self.__count
a=EGG()
a.get_count()
a.set_count()
a.del_count()
但是对操纵者来说不希望这样的体验更改后
class EGG:
__count=0
def get_count(self):
return self.__count
def set_count(self,num):
self.__count=num
def del_count(self):
del self.__count
使用property(get,set,del)
count=property(get_count,set_count,del_count)
class EGG:
__count=0
@property
def count(self):
return self.__count
@count.setter
def count(self,num):
self.__count=num
@count.deleter
def count(self):
del self.__count
a=EGG()
a.count()
a.count(1)
a.count()
提升了体验