Python by Structure: Property Decorators and Managed Attributes
Python by Structure: Property Decorators and Managed Attributes # python # coding # programming # software Timothy was adding a Rectangle class to a geometry library when he ran into a design problem. "Margaret, I need an area attribute on my rectangles, but the area depends on width and height. Should I calculate it in __init__ and store it, or make users call an area() method every time?" Margaret looked at his dilemma. "Neither. You want the area to look like an attribute but calculate itself automatically. That's what the @property decorator does." "Wait," Timothy said. "I thought decorators were for wrapping functions or transforming classes. How does a decorator make something look like an attribute?" The Problem: Methods or Attributes? Margaret showed him the traditional approach: class Rectangle : def __init__ ( self , width , height ): self . width = width self . height = height ...