There is a class:

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 

It is necessary that when trying to access the module variable, the result of executing the hypotenuse method is hypotenuse :

 >>> vector = Vector(3, 4) >>> vector.module 5 >>> vector.x = 5 >>> vector.y = 12 >>> vector.module 13 

those. the value of the variable will be recalculated every time you try to access it

PS I heard something about the decorators, but I really haven't figured it out yet.

  • And why is this necessary? It somehow not on OOP. - Mikhail Vaysman
  • one
    Why is "property" not OOP? - Arnial

1 answer 1

I think you are looking for a property

 class Vector: def __init__( self, x, y ): self.x = x self.y = y @property def module( self ): return (self.x**2 + self.y**2) ** 0.5 v = new Vector(2,2) print( v.module ) # will be 2.8284271247461903 vx = 3 print( v.module ) # will be 3.605551275463989