Distinguish instance-specific values from attributes stored on the class.
How It Works
Class attributes are found through the class or instances; instance attributes can shadow those names. Mutable class attributes are shared unless explicitly replaced, so per-instance lists usually belong inside __init__().
A class attribute is convenient for defaults and constants.
Step-by-Step Example
class SupportTicket:
department = "IT"
def __init__(self, ticket_number):
self.ticket_number = ticket_number
first_ticket = SupportTicket(100)
second_ticket = SupportTicket(101)
print(first_ticket.department == second_ticket.department)
print(first_ticket.ticket_number, second_ticket.ticket_number)
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The expression '"IT"' supplies the value stored as 'department'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
True
100 101
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Give two objects separate names and a shared organization label.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Using a shared class-level list for data that should be private to each instance.
- Assuming assigning an attribute to one instance changes the class attribute for all.
Key Takeaways
- Distinguish instance-specific values from attributes stored on the class.
- Class attributes are found through the class or instances; instance attributes can shadow those names.
- A class attribute is convenient for defaults and constants.