Providing Computed Attributes
00:23 The main reason for creating eager attributes is to optimize computation costs when you access the attribute often. On the other hand, if you rarely use a given attribute, then a lazy property can postpone its computation until needed, which can make your programs more efficient.
On-screen is an example of how to use
property() to create a computed attribute
.area in a
Rectangle class. Here, the
Rectangle initializer takes
height as arguments and stores them in regular instance attributes.
Another common use case of properties is to provide an auto-formatted value for a given attribute. In this example,
.price is a property that formats and returns the price of a particular product.
To provide a currency-like format, you use an f-string with appropriate formatting options. Note that for brevity, this example uses floating-point numbers to represent currencies, which is generally considered bad practice. Instead, you should use
decimal.Decimal from the standard library.
You want to provide polar coordinates for your point so that you can use them in a few computations. The polar coordinate system represents each point using the distance to the origin and the angle with the horizontal coordinate axis. On-screen, you’ll see a Cartesian coordinates
Point class that also provides computed polar coordinates.
When it comes to providing computed or lazy attributes,
property() is a handy tool. However, if you’re creating an attribute that you use frequently, then computing it every time can be costly and wasteful.
Become a Member to join the conversation.