This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 5: Advanced Python type features

Data Classes

face Josiah Wang

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
class Person:
    def __init__(self, name, age=0): 
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"

    def greet(self):
        print(f"Hi! My name is {self.name}!")

lecturer = Person("Josiah", 20)
print(lecturer) # Person(name='Josiah', age=20)
print(lecturer.name) # Josiah
print(lecturer.age) # 20

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
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int = 0 

    def greet(self):
        print(f"Hi! My name is {self.name}!")

lecturer = Person("Josiah", 20)
print(lecturer) # Person(name='Josiah', age=20)
print(lecturer.name) # Josiah
print(lecturer.age) # 20

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!