2-Minute Python Guide: dataclasses
Python's @dataclass decorator is a powerful tool for creating classes that mainly hold data. But how does it compare to a regular class? Let's take a look.
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})"
person = Person("John", 30)
print(person) # Person(name=John, age=30)
Now, let's create the same class using @dataclass:
from dataclasses import dataclass, field
@dataclass
class Person:
name: str
age: int
occupation: str = field(default="Unknown")
person = Person("John", 30)
print(person) # Person(name='John', age=30, occupation='Unknown')
Notice how @dataclass automatically generates __init__ and __repr__ methods for us. We can also use the field function to specify default values.
If we want to make our class immutable, we can use the frozen=True parameter:
@dataclass(frozen=True)
class Person:
name: str
age: int
person = Person("John", 30)
try:
person.name = "Jane"
except FrozenInstanceError:
print("Cannot modify a frozen instance")
Takeaway: The @dataclass decorator is a convenient way to create classes that mainly hold data, with features like automatic method generation and immutability. Use it to simplify your code and make your data classes more readable and maintainable.
Follow me on Dev.to for daily Python tips and quick guides!
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)