Need Assistance?

support@tutorialshub.in

Object-Oriented Python

Properties and encapsulation

ADVERTISEMENT
Python Free Lesson
5 min read
ADVERTISEMENT

Reducing boilerplate for data objects

Dataclasses are useful when a class mainly represents structured data. The @dataclass decorator can generate an initializer, representation and comparison methods according to the options you choose.

Defaults and factories

Immutable defaults such as numbers and strings are straightforward. For mutable fields such as lists, use default_factory so every instance receives its own collection rather than sharing one list.

Dataclass versus ordinary class

Use a dataclass when its generated behavior matches your model. Use a normal class when lifecycle rules, complex invariants or custom behavior make explicit methods more appropriate.

Practice: define an OrderItem dataclass and add a method that returns its line total from quantity and unit price.

ADVERTISEMENT