class E-book:
'''Object for monitoring bodily books in a set.'''
def __init__(self, title: str, weight: float, shelf_id:int = 0):
self.title = title
self.weight = weight # in grams, for calculating transport
self.shelf_id = shelf_id
def __repr__(self):
return(f"E-book(title={self.title!r},
weight={self.weight!r}, shelf_id={self.shelf_id!r})")
The largest headache right here is that you will need to copy every of the arguments handed to __init__ to the article’s properties. This isn’t so unhealthy in case you’re solely coping with E-book, however what you probably have further courses—say, a Bookshelf, Library, Warehouse, and so forth? Plus, typing all that code by hand will increase your possibilities of making a mistake.
Right here’s the identical class carried out as a Python dataclass:
from dataclasses import dataclass
@dataclass
class E-book:
'''Object for monitoring bodily books in a set.'''
title: str
weight: float
shelf_id: int = 0
Whenever you specify properties, referred to as fields, in a dataclass, the @dataclass decorator mechanically generates all of the code wanted to initialize them. It additionally preserves the sort info for every property, so in case you use a linting too that checks sort info, it can be certain that you’re supplying the precise sorts of variables to the category constructor.
