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
Question 1

Why should allowed statuses be a class constant instead of recreated per object?

Hint

Think single source of truth.

Question 2

Code task: implement constructor validation.

class Report:
    STATUSES = {"open", "in_progress", "resolved"}

    def __init__(self, report_id, status):
        # TODO
        pass

Raise ValueError("invalid status") if status is not allowed.

Submission format: submit the full class snippet shown above with # TODO/pass replaced.

Hint

Check membership in self.STATUSES first.

Starter code is prefilled; replace TODO blocks with your solution.
2 test cases will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Question 3

Which statement correctly contrasts __str__ and __repr__?

Hint

One is friendly display, one is technical representation.

Question 4

Code task: implement ordering by priority.

class Ticket:
    def __init__(self, title, priority):
        self.title = title
        self.priority = priority

    def __lt__(self, other):
        # TODO
        pass

Lower priority means more urgent.

Submission format: submit the full class snippet shown above with # TODO/pass replaced.

Hint

Return a boolean from priority comparison.

Starter code is prefilled; replace TODO blocks with your solution.
2 test cases will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Python OOP
  • Difficulty: Beginner
  • Completed: 3 users
Creator
Pavel
Pavel