之前我们讨论过装饰器,如果funa作为funb的装饰器,那么funb=funa(funb),在不改变funb内容的前提下修改了funb的方法。
类中如何定义装饰器,它的作用是什么?
看一段例子:
class test :
def __init__(self, area) :
self.__area = area
@property
def area(self) :
return self.__area
my_test = test(20)
print("ans is", my_test.area)
@property将类中的方法area装饰为一个成员,直接从外部调用。property装饰器下的方法是只读的,即不能从外部修改方法。
如何使得被装饰的方法变为一个从外部可读可写的成员呢?
@方法名.setter
方法名(self, value)
class test :
def __init__(self, area) :
self.__area = area
@property
def area(self) :
return self.__area
@area.setter
def area(self, value) :
self.__area = value
my_test = test(20)
my_test.area = 90
print("ans is", my_test.area)