Advanced Lesson 3
Advanced Object-Oriented Programming
Chapter 5: Advanced Python type features
Data Classes
So far, here is how you might define your classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
You might have written code like Lines 3-4 quite a lot. These are quite repetitive, are they not? Perhaps there is some way to automate this so that you do not have to type these each time you define a class.
The __repr__()
method can perhaps also be automated to return all the attributes of Person
?
Data classes for the lazy people!
Python introduced data classes in Python 3.7. What dataclasses
does is to save you from having to manually write repetitive things as described above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Same output as before, but with less code!
There are more things you can do with dataclasses
. We will not discuss more – please see the official documentation and explore it on your own if you are interested to use this more often!