From the course: Advanced Python

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Computed attributes

Computed attributes - Python Tutorial

From the course: Advanced Python

Start my 1-month free trial

Computed attributes

- [Instructor] In the previous example, we saw how to use special Python class methods to generate string representation of objects. In this example, we'll take the customization a step further. Python provides a set of methods that classes can use to control how attributes are accessed on an object. Whenever an object's attributes are retrieved or set, Python calls one of these functions to give your class an opportunity to perform any desired processing. The first two, getattribute and getattr, are called to retrieve an attribute value. Now these are slightly different from each other, but it's important to know the difference. Getattr is called only when the requested attribute can't be found on the object, while getattribute is called unconditionally every time an attribute name is requested. It's also called by Python when it goes to look up any methods on your class, so you need to be really careful with it. The setattr function is called when an attribute value is set on the…

Contents