In Python, both classes and data classes are blueprints for creating objects, but they have distinct purposes and features.
Classes:
- General-purpose: Classes are versatile and allow you to define attributes (data) and methods (functions) to represent real-world entities.
- Flexibility: You have complete control over the structure and behavior of objects created from a class.
- Customization: You can add custom methods and logic to handle specific actions and interactions.
Example:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.name) # Output: Buddy
my_dog.bark() # Output: Woof!
Data Classes:
- Data-centric: Data classes are primarily used for storing data, making them ideal for representing simple structures.
- Conciseness: They automatically generate methods like
__init__
,__repr__
, and__eq__
, simplifying data handling. - Immutability: You can define attributes as immutable, ensuring data integrity.
Example:
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
quantity: int
product1 = Product("Laptop", 1200.00, 2)
print(product1) # Output: Product(name='Laptop', price=1200.0, quantity=2)
In summary:
- Use classes for general-purpose object creation, complex logic, and customization.
- Use data classes for storing and representing data in a concise and structured manner.