有一类:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
self.module = (x**2 + y**2) ** 0.5
def hypotenuse(self):
return (self.x**2 + self.y**2) ** 0.5
有必要在尝试访问变量时module
返回方法执行的结果hypotenuse
:
>>> vector = Vector(3, 4)
>>> vector.module
5
>>> vector.x = 5
>>> vector.y = 12
>>> vector.module
13
那些。每次你尝试访问它时,变量的值都会被重新计算
PS 我听说过装饰器,但我还没有真正弄明白
我想你在找
property