我们都知道property
是将类的方法变成属性的装饰器
>>> class Circle:
... def __init__(self, radius):
... self.radius = radius
... @property
... def perimeter(self):
... return 2 * self.radius * 3.14
... @property
... def area(self):
... return self.radius**2 * 3.14
...
>>> test = Circle(2)
>>> test.perimeter
12.56
>>> test.area
12.56
有时候我们想隐藏一些内部的属性,不让外部可以调用和更改。我们创建了以下类方法
>>> class Test:
... def __init__(self, name):
... self.__name = name
... @property
... def name(self):
... return self.__name
...
>>> aa = Test('eclipse')
>>> aa.name
'eclipse'
>>> aa.name = '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
此时,我们无法在外部修复其属性,这时候我们需要扩展propery
方法,如下:
>>> class Test:
... def __init__(self, name):
... self.__name = name
... @property
... def name(self):
... return self.__name
... @name.setter
... def name(self, new_name):
... self.__name = new_name
...
>>> bb = Test('eclipse')
>>> bb.name
'eclipse'
>>> bb.name = 'Python'
>>> bb.name
'Python'
>>>
我们还可以扩展property
的deleter
方法,用于删除该属性值。用的不多,这里不说了。
网友评论