Dataclasses

Dataclasses are basically regular objects w

ith a clean syntax for predefining attributes. There are a few ways to create one, and we'll explore each in this section.

The simplest way is to use a similar construct to that used for named tuples, as follows:

from dataclasses import make_dataclassStock = make_dataclass("Stock", "symbol", "current", "high", "low")stock = Stock("FB", 177.46, high=178.67, low=175.79)

Once instantiated, the stock object can be used like any regular class. You can access and update attributes and can even assign other arbitrary attributes to the object, as follows:

>>> stockStock(symbol='FB', current=177.46, high=178.67, low=175.79)>>> stock.current177.46>>> stock.current=178.25>>> stockStock(symbol='FB', ...

Get Python 3 Object-Oriented Programming. - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.