Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Providing Computed Attributes

00:00 Providing Computed attributes. If you need an attribute that builds its value dynamically whenever you access it, then property() is the way to go.

00:12 These kinds of attributes are commonly known as computed attributes. They’re handy when you need them to look like eager attributes, but you want them to be lazy.

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.

00:40 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 width and height as arguments and stores them in regular instance attributes.

00:54 The read-only property .area computes and returns the area of the current rectangle every time you access it.

01:03 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.

01:16 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.

01:37 As a final example of computed attributes, let’s say you have a Point class that uses .x and .y as Cartesian coordinates.

01:44 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.

02:51 This shows how to compute the distance and angle of a given Point object using its .x and .y Cartesian coordinates.

03:02 Here’s how it works in practice.

03:32 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.

03:46 A good strategy is to cache them once the computation is done, and that’s what you’ll see in the next section of the course.

Become a Member to join the conversation.