← Python lessons

Python Dataclass Methods: Add Behaviour to Fields

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A Python dataclass method is an ordinary method inside a @dataclass class. The decorator generates __init__() from the fields; your methods use them through self.

Read Python Dataclasses and Methods and self first. This lesson adds your own methods to the generated ones.

Add behaviour to generated fields

Write the fields first, then the methods, in the same class body.

from dataclasses import dataclass@dataclassclass Box:    width: int    height: int    def area(self):        return self.width * self.heightbox = Box(3, 4)print(box)print(box.area())

This prints Box(width=3, height=4), then 12. The generated __init__() stored 3 and 4, and area() reads them through self. Call it with brackets: box.area without them is the method itself, not 12.

Replace a hand-written init

A plain class copies each argument onto self by hand. A dataclass generates that code from its fields.

from dataclasses import dataclassclass PlainBox:    def __init__(self, width, height):        self.width = width        self.height = height@dataclassclass Box:    width: int    height: intprint(PlainBox(3, 4).width, Box(3, 4).width)print(PlainBox(3, 4) == PlainBox(3, 4), Box(3, 4) == Box(3, 4))

Both classes store 3 in width. Only the dataclass compares objects by their field values, so the second line prints False True. Choose a dataclass when a class mainly holds data. Write __init__() yourself when creating an object must do more than store the arguments.

Change fields in a method

A method can also update a field. The generated display then shows the new value.

from dataclasses import dataclass@dataclassclass Account:    owner: str    balance: int    def deposit(self, amount):        self.balance += amountaccount = Account("Ada", 10)account.deposit(5)print(account)

This prints Account(owner='Ada', balance=15). The method changed the object, so it returns nothing. Return a value when the caller needs a result, like area(). Change a field when the object itself must remember the change, like deposit().

Only names with a type hint become fields

Fields and other names in the class body look alike, but @dataclass treats them differently. A field has a type hint: it becomes an argument of __init__() and appears in the display. A method, or a name without a type hint, is not a field.

from dataclasses import dataclass@dataclassclass Box:    width: int    height = 4  # no type hint, so this is a class attribute, not a field    def area(self):        return self.width * self.heightprint(Box(3))print(Box(3).area())print(Box(3, 5))  # this line raises TypeError: the constructor takes only width

Box(3) displays as Box(width=3), and its area() is 12. Neither height nor area is a field, so passing a second argument fails.

Note: These examples keep values simple. Type hints do not check values at runtime, so Box("3", 4) is accepted. Defaults and lists of values are covered in Python Dataclasses.

See also: Type hints, Classes and objects.

Your turn

Add a method add_points(points) to Player that raises its score by points. Then give ada 5 points and 3 points and print her.

🎯 Goal — make it print exactly:
Player(name='Ada', score=18)
from dataclasses import dataclass@dataclassclass Player:    name: str    score: int    # add the method add_points(self, points): it adds points to self.scoreada = Player("Ada", 10)# add two lines: give ada 5 points, then 3 pointsprint(ada)