Classes, Objects, Constants, and Magic Methods
Beginner
Python OOP
Created by Pavel
· 12.03.2026 at 07:54 UTC
· 3 completed
Object-oriented programming is most useful when each class models one domain concept with clear responsibilities.
A class can contain:
- instance attributes (self.x): data that differs per object,
- class constants (ClassName.X): shared values reused by all objects,
- methods: behavior that uses that data.
Why class constants matter:
- avoid duplicated data in every instance,
- centralize domain rules,
- reduce inconsistent hard-coded values.
Example:
class Report:
STATUSES = {"open", "in_progress", "resolved"}
def __init__(self, report_id, status):
if status not in self.STATUSES:
raise ValueError("invalid status")
self.report_id = report_id
self.status = status
Magic methods used frequently:
- __init__: initialize state,
- __str__: human-readable text,
- __repr__: debug/developer representation,
- __lt__: custom ordering for sorting.
Edge case: constructor should reject invalid input immediately to keep object state valid.
University approvals: 0
Tasks
Card Info
- Topic: Python OOP
- Difficulty: Beginner
- Completed: 3 users
Creator
Pavel