Replacing Getters and Setters With More Advanced Tools
00:00 Using More Advanced Tools. Up to this point, you’ve learned how to create bare-bones getter and setter methods to manage the attributes of your classes. You’ve also learned that properties are the Pythonic way to approach the problem of adding functional behavior to existing attributes.
00:16 In this part of the course, you’ll learn about other tools and techniques that you can use to replace getter and setter methods in Python. Descriptors are an advanced Python feature that allow you to create attributes with attached behaviors in your classes.
01:44 The class works as expected. However, it does start to look repetitive and boring, so you decide to refactor the class. You notice that you are doing the same operation in both date-related attributes, and you think of using a descriptor to pack the repetitive functionality.
In general, if you find yourself cluttering up your classes with similar property definitions, then you should consider using a descriptor instead. Another way to replace traditional getter and setter methods in Python is to use the
.__getattr__() special methods to manage your attributes.
To do this, the method uses the instance namespace dictionary,
.__dict__. Note that the attribute’s final name will have an underscore preceding whatever you pass in
name. Python automatically calls
.__getattr__() whenever you access an attribute of
Point using dot notation.
.__setattr__() method adds or updates attributes. In this example,
.__setattr__() operates on each coordinate and converts it into a floating-point number using the built-in
float() function. Again, Python calls
.__setattr__() whenever you run an assignment operation on any attribute of the containing class. On-screen, you can see how the class works in practice.
The example in this section is a little bit unusual, and you probably won’t use something similar in your own code. However, the tools that you’ve used in the example allow you to perform validations or transformations on attribute access and mutation, just like getter and setter methods do. In a sense,
.__setattr__() are a generic implementation of the getter and setter pattern. Under the hood, these methods work as getters and setters that support regular attribute access and mutation in Python. In the next section of the course, you’ll take a look at some of the factors you should think about when deciding which of the techniques you’ve seen in this course will be used in your code.
Become a Member to join the conversation.