Need to represent tasks with their own data and operations? Define a class. A class is a Python type: calling it creates an instance, and its attributes and methods give that instance a useful shape. Built-in types such as list and dict are classes too. A custom class lets an application model needs that generic containers do not express well. section 5.1 section 8.0
Initialize a task
class Task: def __init__(self, title, desc, urgency): self.title = title self.desc = desc self.urgency = urgency task = Task("Laundry", "Wash clothes", 3) print(task.__dict__) # {'title': 'Laundry', 'desc': 'Wash clothes', 'urgency': 3} Calling Task creates an instance; __init__ sets its essential attributes from the supplied arguments. Put __init__ first and initialize every instance attribute there, even when an initial value must be None. That makes the available data easier to discover. section 8.1.2 section 8.1.5
Choose the shape that fits the job:
- For a lightweight data holder, compare a custom class with a named tuple. Lists and tuples obscure field meanings; dictionary keys name fields but can be mistyped. A class becomes especially useful when data needs related methods. section 3.3.1 section 8.0
- Use instance methods for instance behavior, class attributes for values shared by all instances, and static or class methods where those method forms fit. Properties can control changes to data; __str__ and __repr__ provide useful string representations. section 8.6
- Use @dataclass to avoid routine __init__ and __repr__ boilerplate. For a set of enumerated values, subclass Enum rather than treating integer-valued class attributes as enumeration members. section 9.1.1 section 9.6
Use a class as a type hint
class User: pass def assign_task(pending_task: Task, user: User): pass A defined custom class can name an expected parameter type just as a built-in type can. Here pass is only a placeholder: real methods need implementations. section 6.3.3
Keep each class focused on one purpose. If a large class mixes, for example, account and demographic responsibilities, group its attributes and methods by function, then consider splitting it into distinct classes. A UML diagram can make that structure visible. Test a class chiefly through its methods, and revisit its design as the project grows; related classes should work together without becoming tightly coupled. section 9.5.1 section 9.5.4 section 13.4




















