class Guide:
'''Object for monitoring bodily books in a group.'''
def __init__(self, title: str, weight: float, shelf_id:int = 0):
self.title = title
self.weight = weight # in grams, for calculating delivery
self.shelf_id = shelf_id
def __repr__(self):
return(f"Guide(title={self.title!r},
weight={self.weight!r}, shelf_id={self.shelf_id!r})")
The largest headache right here is that you could copy every of the arguments handed to __init__
to the thing’s properties. This isn’t so dangerous should you’re solely coping with Guide
, however what when you have further lessons—say, a Bookshelf
, Library
, Warehouse
, and so forth? Plus, typing all that code by hand will increase your probabilities of making a mistake.
Right here’s the identical class carried out as a Python dataclass:
from dataclasses import dataclass
@dataclass
class Guide:
'''Object for monitoring bodily books in a group.'''
title: str
weight: float
shelf_id: int = 0
Once you specify properties, referred to as fields, in a dataclass, the @dataclass
decorator robotically generates all of the code wanted to initialize them. It additionally preserves the sort info for every property, so should you use a linting too that checks kind info, it should make sure that you’re supplying the suitable sorts of variables to the category constructor.