🎓 All Courses | 📚 Python Programming Syllabus

📋 Study this course on TaskLoco
#python-programming#dataclasses#oop

Data Classes — Cleaner Class Definitions

Python 3.7+ @dataclass decorator auto-generates __init__, __repr__, and __eq__.


Without dataclass:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"

With dataclass:

from dataclasses import dataclass, field

@dataclass
class Point:
    x: float
    y: float

p = Point(1.0, 2.0)
print(p)  # Point(x=1.0, y=2.0)
p1 == p2  # compares by value automatically

Defaults & post-init:

@dataclass
class Student:
    name: str
    grade: int = 0
    courses: list = field(default_factory=list)

    def __post_init__(self):
        self.name = self.name.title()

Frozen (immutable) dataclass:

@dataclass(frozen=True)
class Color:
    r: int
    g: int
    b: int

YouTube • Top 10
Python Programming: Data Classes
Tap to Watch ›
📸
Google Images • Top 10
Python Programming: Data Classes
Tap to View ›

Reference:

Wikipedia: Python

image for linkhttps://en.wikipedia.org/wiki/Python_(programming_language)

📚 Python Programming — Full Course Syllabus
📋 Study this course on TaskLoco

TaskLoco™ — The Sticky Note GOAT