Using Properties Instead of Getters and Setters
00:00 Using Properties Instead of Getters and Setters. The Pythonic way to attach behavior to an attribute is to turn the attribute itself into a property. Properties pack together methods for getting, setting, deleting, and documenting the underlying data. Therefore, properties are special attributes with additional behavior.
00:22 You can use properties in the same way that you use regular attributes. When you access a property, its attached getter method is automatically called. Likewise, when you mutate the property, its setter method gets called.
This behavior provides the means to attach functionality to your attributes without introducing breaking changes in your code’s API. As an example of how properties can help you attach behavior to attributes, let’s say you need an
Employee class as part of an employee management system.
You’ve added behavior to the
.birth_date attributes without affecting your class’s API. With properties, you’ve gained the ability to refer to these attributes as you would to regular attributes. Behind the scenes, Python takes care of running the appropriate methods for you.
04:03 Properties are officially recommended in PEP 8 as the right way to deal with attributes that need functional behavior. Python’s properties have a lot of potential use cases. For example, you can use properties to create read-only, read-write, and write-only attributes in an elegant and straightforward manner.
04:24 Properties allow you to delete and document the underlying attributes and more. More importantly, properties allow you to make regular attributes behave like manage attributes with attached behavior without changing the way that you work with them. Because of properties, Python developers tend to design their classes’ APIs using a few guidelines.
04:55 You can always turn them into properties if needed. Use properties when you need to attach behavior to attributes and keep using them as regular attributes in your code. And avoid side effects in properties because no one would expect operations such as assignments to cause any side effects. Python’s properties are useful, but because of that, people tend to overuse them. In general, you should only use properties when you need to add extra processing on top of a specific attribute.
05:25 Turning all of your attributes into properties will be a waste of your time. It may also create performance and maintainability issues. In the next section of the course, you’ll take a look at more advanced tools you can use to replace getter and setter methods in Python.
Become a Member to join the conversation.