Understanding Methods in Python Classes
A method is a function defined inside a class that operates on instances (or the class itself). Methods define the behavior of objects and are the primary way objects interact with the world.
Three Types of Methods
The most common type. They:
- Take
selfas the first parameter (referring to the instance). - Can access and modify instance attributes.
- Can access class attributes via
self.__class__or the class name.
class Student:
school = "Global Academy" # Class attribute
def __init__(self, name, grade):
self.name = name # Instance attribute
self.grade = grade
def introduce(self): # Instance method
return f"I'm {self.name}, Grade {self.grade} at {self.school}"
s = Student("Layla", 10)
print(s.introduce()) # I'm Layla, Grade 10 at Global Academy@classmethod)Bound to the class, not instances. They:
- Take
clsas the first parameter (referring to the class). - Can access or modify class state.
- Commonly used for alternative constructors.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_birth_year(cls, name, birth_year):
current_year = 2024
age = current_year - birth_year
return cls(name, age) # Creates new instance
p = Person.from_birth_year("Khalid", 1995)
print(p.age) # 29@staticmethod)Not bound to class or instance. They:
- Don’t take
selforcls. - Behave like regular functions but belong to the class namespace.
- Used for utility functions logically related to the class.
class Temperature:
def __init__(self, celsius):
if not Temperature.is_valid(celsius):
raise ValueError("Invalid temperature")
self.celsius = celsius
@staticmethod
def is_valid(temp):
return -273.15 <= temp <= 1000 # Absolute zero to 1000°C
def to_fahrenheit(self):
return (self.celsius * 9/5) + 32
t = Temperature(25)
print(t.to_fahrenheit()) # 77.0Inheritance: Building Hierarchies
Inheritance allows a class (child or subclass) to inherit attributes and methods from another class (parent or superclass). This promotes code reuse and establishes "is-a" relationships.
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine(self):
return f"{self.brand} {self.model} engine started."
class Car(Vehicle): # Car inherits from Vehicle
def __init__(self, brand, model, doors):
super().__init__(brand, model) # Call parent constructor
self.doors = doors
def honk(self):
return "Beep beep!"
my_car = Car("Toyota", "Camry", 4)
print(my_car.start_engine()) # Inherited method
print(my_car.honk()) # New methodThe super() Function
super() gives access to methods and properties of a parent class. It’s essential for:
- Calling the parent’s
__init__to initialize inherited attributes. - Extending (not replacing) parent behavior in overridden methods.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
class Dog(Animal):
def speak(self):
# Extend parent behavior
parent_sound = super().speak()
return parent_sound + " Woof!"
dog = Dog("Buddy")
print(dog.speak())
# Buddy makes a sound. Woof!Method Resolution Order (MRO)
In multiple inheritance, Python uses the C3 linearization algorithm to determine which method to call. The order is visible via ClassName.__mro__.
class A:
def greet(self):
return "Hello from A"
class B(A):
def greet(self):
return "Hello from B"
class C(A):
def greet(self):
return "Hello from C"
class D(B, C):
pass
d = D()
print(d.greet()) # Hello from B
print(D.__mro__)
# (, , , , ) Overriding vs. Overloading
- Overriding: Redefining a method in a subclass (supported in Python).
- Overloading: Defining multiple methods with the same name but different parameters (not natively supported; use default args or
*argsinstead).
class Calculator:
def add(self, a, b, c=0):
return a + b + c
calc = Calculator()
print(calc.add(1, 2)) # 3
print(calc.add(1, 2, 3)) # 6Abstract Base Classes (ABCs) & Enforcing Contracts
Use the abc module to define interfaces that subclasses must implement.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
# rect = Shape() → TypeError! Cannot instantiate abstract classBest Practices
- ✅ Use
super()consistently—especially in__init__. - ✅ Favor composition over deep inheritance—shallow hierarchies are easier to maintain.
- ✅ Document method signatures and expected behavior clearly.
- ✅ Use abstract base classes to define clear contracts for subclasses.
- ✅ Avoid multiple inheritance unless absolutely necessary—it complicates MRO.
Common Pitfalls
- ❌ Forgetting to call
super().__init__()in subclass constructors. - ❌ Overriding methods without understanding the parent’s contract.
- ❌ Creating diamond inheritance problems without understanding MRO.
- ❌ Using inheritance just to reuse code—consider composition instead.
Key Takeaways
- Methods define object behavior: instance, class, and static serve distinct purposes.
- Inheritance enables code reuse and modeling of "is-a" relationships.
super()is crucial for proper initialization and method extension.- Python’s MRO resolves method calls in complex hierarchies predictably.
- Use abstract base classes to enforce interface contracts in large systems.