79453698

Date: 2025-02-20 07:58:14
Score: 1
Natty:
Report link

@dataclass makes it easy to create classes for storing data without writing extra code. It automatically create init(), and other methods which makes your code cleaner and more readable. For Example: If you make a class to store data, you have to write:

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

name = name
        self.age = age

    def __repr__(self):  # So we can print the object nicely
        return f"Person(name='{self.name}', age={self.age})"

p1 = Person("Alice", 25)
print(p1)  # Output: Person(name='Alice', age=25)

Too much code for just simple task, but using @dataclass we can make it alot simpler:

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

p1 = Person("Alice", 25)
print(p1)  # Output: Person(name='Alice', age=25)
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @dataclass
  • User mentioned (0): @dataclass
  • Low reputation (1):
Posted by: Fatima Riaz