Defining Methods: Instance, Class, and Static Methods
Lesson Overview
This lesson breaks down the three ways to define behaviors in a class: Instance Methods (for actions on specific objects), Class Methods (for actions related to the class blueprint itself), and Static Methods (for general utility tasks related to the class but independent of specific data).
Lesson Content
Functions (The Tools You Already Know)
You are already familiar with functions. They are standalone blocks of code designed to perform a general task. You give them data (arguments), they process it, and return a result. They are like general tools in a toolbox—anyone can use a hammer on anything.
Example: len() is a pre-defined function in python. You can give it a string, a list, or a dictionary, and it will tell you the length. It doesn't belong to the list or string or dict. it's a separate tool that can be used on allowed data-types .
# Using a function
my_list = [1, 2, 3]
print(len(my_list)) # Output: 3
name = "Farooq"
print(len(name)) # Output: 6Introducing Methods
Methods are functions, but with a twist: they are defined inside a class and are attached to the objects created from that class. Think of a method as a skill or ability that belongs to a specific object.
Why are Methods Useful?
Why do we need methods if we already have functions?
- Context Awareness (The 'Self' Advantage):
- Function: You have to manually pass every piece of data to it.
drive_car(my_car_color, my_car_model)-> You have to remind the function which car you are talking about.
- Method: It already knows the data because it lives inside the object.
my_car.drive()-> You just say "drive," and the car knows its own color and model automatically usingself.
- Function: You have to manually pass every piece of data to it.
- Organization:
- Methods keep related code together. All "Car" abilities (driving, honking, stopping) are neatly packed inside the
Carclass. This makes your code organized and easier to manage than having hundreds of loose functions floating around.
- Methods keep related code together. All "Car" abilities (driving, honking, stopping) are neatly packed inside the
Now that you understand what methods are, let's talk about a special method called __init__, commonly referred to as the constructor.
The Constructor Method :
The __init__ method is a special method that runs automatically the moment you create a new object from a class. Its primary job is to initialize (set up) the object's attributes with starting values, preparing the object for use. Think of it as the birth certificate of an object—it records the essential details (like name, color, model) right when the object comes into existence.
class Car:
def __init__(self, color, model):
# This code runs automatically when you create a Car object
self.color = color # Initialize the color attribute
self.model = model # Initialize the model attribute
# Creating an object - __init__ runs automatically
my_car = Car("Red", "Maruti Shift")Almost Every Class Has __init__
Almost every class you write will have an __init__ method because objects almost always need some initial data to be useful. Just like a newborn needs a name and birth details, a Car object needs a color and model, and a BankAccount object needs an initial balance. The __init__ method is where you provide these essential starting values
Other Methods - Instance, Class, and Static Methods
Understanding Methods with a Factory Analogy
Imagine a Car Factory. To understand the different types of methods, let's look at who does what in this factory:
- The Workers (Instance Methods): They work on one specific car at a time. A worker paints this car red or changes that car's tires. They need access to the specific car they are working on.
- The Factory Manager (Class Methods): The manager looks at the entire production line. They don't focus on one single car but manage things that affect all cars, like setting the global safety standard or tracking the total number of cars built.
- The Tool Maintenance Crew (Static Methods): They fix tools or check weather conditions for shipping. Their job is useful to the factory, but they don't touch the cars or talk to the manager directly. They just do their specific task independently.
1. Instance Methods (The Workers)
These are the most common methods. They act on a specific object (instance). They need the self parameter to know which object's data to use or to change.
class Car:
def __init__(self, model):
# This code runs automatically when you create a Car object
self.color = color # Initialize the color attribute
self.model = model # Initialize the model attribute
def drive(self): # Instance method
print(f"The {self.model} is driving now.")
my_car = Car("Red", "Maruti Shift")
my_car.drive() # Output: The Maruti Shift is driving now.
other_car = Car("Blue", "Skoda")
other_car.drive() # Output: The Skoda is driving now.Even though we don't pass any arguments when calling my_car.drive(), the method can still access and use the object's data (like self.model). This is the power of instance methods— they automatically have access to all the object's attributes through the self parameter, which Python passes invisibly behind the scenes.
The method "knows" which car it belongs to and can use that car's specific data (color, model, mileage) without you having to manually pass it every time.
2. Class Methods (The Manager)
These methods work with the class itself, not a specific object. They use cls instead of self. They are often used to track things common to all objects
class Car:
total_cars = 0 # Class variable
def __init__(self, model):
# This code runs automatically when you create a Car object
self.color = color # Initialize the color attribute
self.model = model # Initialize the model attribute
Car.total_cars += 1
def drive(self): # Instance method
print(f"The {self.model} is driving now.")
@classmethod #This decorator is must and needed
def show_total_cars(cls): # Class method
print(f"Total cars built: {cls.total_cars}")
my_car = Car("Red", "Maruti Shift")
other_car = Car("Red", "Skoda")
Car.show_total_cars() # Output: Total cars built: 2Think of the Car class as a factory and total_cars as a single digital counter on the factory wall that tracks production. This counter is a Class Variable—it is shared by the entire factory, not owned by any single car. Every time a new car is built (__init__), it updates this central counter. To read this counter, we use a Class Method (marked with @classmethod), which acts like asking the factory manager for a report. Instead of using self (which focuses on one specific car), this method uses cls to look at the factory (the Class) itself. This is why we call Car.show_total_cars() directly on the class—we are asking for the factory's total stats, not a specific car's details.
3. Static Methods (The Utility Tool)
These are utility methods that belong to the class but don't need access to class data (cls) or object data (self). They are just regular functions placed inside a class because they logically belong there.
class Car:
total_cars = 0 # Class variable
def __init__(self, model):
# This code runs automatically when you create a Car object
self.color = color # Initialize the color attribute
self.model = model # Initialize the model attribute
Car.total_cars += 1
def drive(self): # Instance method
print(f"The {self.model} is driving now.")
@classmethod #This decorator is must and needed
def show_total_cars(cls): # Class method
print(f"Total cars built: {cls.total_cars}")
@staticmethod
def km_to_miles(km):
# A utility function that doesn't need self or cls
# It just does a calculation and returns the result
return km * 0.621371
@staticmethod
def is_valid_model(model): # Static method
valid_models = ["Sedan", "SUV", "Truck"]
return model in valid_models
print(Car.is_valid_model("Convertible")) # Output: FalseA Static Method is like a generic tool attached to the class for convenience, but it doesn't actually need access to the class (cls) or any specific object (self) to do its job. It's a helper function that logically belongs in the class but works independently—like a calculator or a converter sitting on the factory manager's desk.
Summary Table
| Method Type | First Parameter | Access Level | Analogy |
| Instance Method | self | Can change object & class state | Worker working on a specific car |
| Class Method | cls | Can change class state only | Manager overseeing the factory |
| Static Method | None | Cannot change state (Independent) | Tools that are used by Maintenance crew |