
"Everything in Python is an object, or so the saying goes. If you want to create your own custom objects, with their own properties and methods, you use Python's class object to do it. But creating classes in Python sometimes means writing loads of repetitive, boilerplate code; for example, to set up the class instance from the parameters passed to it or to create common functions like comparison operators."
"Dataclasses, introduced in Python 3.7 ( and backported to Python 3.6), provide a handy, less-verbose way to create classes. Many of the common things you do in a class, like instantiating properties from the arguments passed to the class, can be reduced to a few basic instructions by using dataclasses. The backstage power of Python dataclasses Consider this example of a conventional class in Python: class Book: '''Object for tracking physical books in a collection.''' def __init__(self, name: str, weight: float, shelf_id:int = 0): self.name = name self.weight = weight # in grams, for calculating shipping self.shelf_id = shelf_id def __repr__(self): return(f"Book(name={self.name!r}, weight={self.weight!r}, shelf_id={self.shelf_id!r})") The biggest headache here is that you must copy each of the arguments passed to __init__ to the object's properties. This isn't so bad if you're only dealing with Book, but what if you have additional classes-say, a Bookshelf, Library, Warehouse, and so on? Plus, typing all that code by hand increases your chances of making a mistake."
Dataclasses simplify creation of Python classes by automatically generating common methods such as __init__, __repr__, and comparison operators based on declared fields. They were introduced in Python 3.7 and backported to 3.6. Declaring attributes as typed fields eliminates manual assignment of constructor arguments to instance properties. Dataclasses reduce repetitive boilerplate across related classes like Bookshelf or Library, lowering the chance of copy-paste errors. The @dataclass decorator derives useful implementations from field definitions and default values. For example, a Book class with name, weight, and shelf_id can be expressed concisely with @dataclass, replacing multi-line __init__ and __repr__ implementations while keeping type annotations.
Read at InfoWorld
Unable to calculate read time
Collection
[
|
...
]