Using properties
Python allows us to create methods that can be used as if they were attributes. This gives us very pleasant syntax for getting a derived value from an object. A method that appears to be an attribute is called a property. We'll extend our Point
class with two more methods:
@property def r(self): return math.sqrt(self.x**2 + self.y**2) @property def θ(self): return math.atan2(self.y, self.x)
We've defined two functions using the @property
decorator. This decorator can be used with a function that has only the instance variable, self
, as a parameter.
Here's how we can use these properties:
>>> p = Point(12, 5) >>> round(p.r, 1) 13.0 >>> round(math.degrees(p.θ), 1) 22.6
We've accessed these methods as if they were simple attributes of the object, p
. Using p.r
and p.
θ can be more pleasant than having to write p.r()
and p.
θ()
in a complex formula. The preceding properties are explicitly read-only. We get an exception if we...