DEV Community

qing
qing

Posted on • Edited on

Master Python in 2 Mins

2-Minute Guide: dataclasses in Python

In Python, dataclasses provide a convenient way to create classes that mainly hold data. Let's compare a regular class with a @dataclass to see the benefits.

Regular Class

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person(name='{self.name}', age={self.age})"
Enter fullscreen mode Exit fullscreen mode

@dataclass

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int
Enter fullscreen mode Exit fullscreen mode

Notice the significant reduction in code.


Follow me on Dev.to for daily Python tips and quick guides!


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*


喜欢这篇文章?关注获取更多Python自动化内容!


If you found this useful, you might like Python Interview Prep Guide — a practical resource that takes things a step further. At $24.99 it's a solid investment for your toolkit.

Top comments (0)