Python Classes, Objects, and Special Methods
Object-Oriented Fundamentals
Object-oriented programming revolves around creating blueprints called classes that define the structure and behavior of objects. A class serves as a template for instantiating individual objects, each with its own distinct state.
Key components of a class definition:
| Component | Description |
|---|---|
class keyword |
Declares the class |
| Class name | Follows PascalCase convention |
| Constructor | __init__ method for initialization |
| Attributes | Instance variables storing state |
| Methods | Functions defining behavior |
Class Declaration
class ClassName:
def __init__(self, param1, param2, param3):
self.field1 = param1
self.field2 = param2
self.field3 = param3
def operation_a(self, arg):
# method body
pass
def operation_b(self):
# method body
pass
Instantiating a class triggers the constructor automatical.
Working Example: Creating a Vehicle Class
class Vehicle:
def __init__(self, brand, year):
self.brand = brand
self.year = year
def show_details(self):
print(f"Brand: {self.brand}, Year: {self.year}")
def start_engine(self):
print(f"The {self.brand} engine is now running.")
# Creating instances
car1 = Vehicle("Toyota", 2022)
car2 = Vehicle("Honda", 2021)
# Invoking methods
car1.show_details() # Output: Brand: Toyota, Year: 2022
car2.start_engine() # Output: The Honda engine is now running.
In this implementation, Vehicle serves as the blueprint. The __init__ constructor accepts brand and year parameters to set up instance attributes. Two instances—car1 and car2—are created with different values.
The Constructor Method
The constructor, defined as __init__, executes immediately when an object is instantiated. Its primary role is establishing the initial state of the newly created object.
Constructor guidelines:
| Guideline | Explanation |
|---|---|
| Naming convention | Must be named exactly __init__ |
| First parameter | Always self, referencing the current instance |
| Additional parameters | Used to populate instance attributes |
class Product:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
def get_total_value(self):
return self.price * self.quantity
# Object creation via constructor
item = Product("Laptop", 999.99, 3)
print(item.get_total_value()) # Output: 2999.97
When Product("Laptop", 999.99, 3) executes, Python invokes __init__, which binds the passed arguments to instance variables.
Dunder Methods
Dunder methods (short for "double underscore") enable custom behavior when Python operators or built-in functions interact with class instances.
| Method | Trigger | Purpose |
|---|---|---|
__init__ |
Object creation | Initialize instance state |
__str__ |
print(), str() |
Human-readable output |
__repr__ |
Debugging, REPL | Unambiguous representation |
__del__ |
Garbage collection | Cleanup operations |
__eq__ |
== comparison |
Define equality logic |
__lt__, __gt__ |
<, > comparison |
Ordering comparisons |
__add__ |
+ operator |
Addition behavior |
__sub__ |
- operator |
Subtraction behavior |
__mul__ |
* operator |
Multiplication behavior |
__len__ |
len() functon |
Return length value |
Enhanced Example with Dunder Methods
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return f"Student: {self.name}, Score: {self.score}"
def __repr__(self):
return f"Student('{self.name}', {self.score})"
def __eq__(self, other):
if isinstance(other, Student):
return self.score == other.score
return NotImplemented
def __lt__(self, other):
if isinstance(other, Student):
return self.score < other.score
return NotImplemented
# Instantiation
student_a = Student("Emma", 85)
student_b = Student("Liam", 92)
student_c = Student("Emma", 85)
# Output demonstrations
print(str(student_a)) # Output: Student: Emma, Score: 85
print(repr(student_b)) # Output: Student('Liam', 92)
print(student_a == student_c) # Output: True
print(student_a < student_b) # Output: True
The __str__ method provides a formatted string suitable for end users. The __repr__ method returns a representation that could theoretically recreate the object. The __eq__ method compares only the score attribute, while __lt__ enables sorting students by their scores.