16. PYTHONIC OOP: PROPERTIES AND DUNDER METHODS

Many languages have OOP features, but Python has some unique OOP features, including properties and dunder methods. Learning how to use these Pythonic techniques can help you write concise and readable code.

Properties allow you to run some specific code each time an object’s attri- bute is read, modified, or deleted to ensure the object isn’t put into an invalid state. In other languages, this code is often called getters or setters. Dunder methods allow you to use your objects with Python’s built-in operators, such as the + operator. This is how you can combine two datetime.timedelta objects, such as datetime.timedelta(days=2) and datetime.timedelta(days=3) , to create a new datetime.timedelta(days=5) object.

In addition to using other examples, we’ll continue to expand the WizCoin class we started in Chapter 15 by adding properties and overload- ing operators with dunder methods. These features will make WizCoin objects more expressive and easier to use in any application that imports the wizcoin module.