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: 6

Introducing 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 using self.
  • Organization:
    • Methods keep related code together. All "Car" abilities (driving, honking, stopping) are neatly packed inside the Car class. This makes your code organized and easier to manage than having hundreds of loose functions floating around.

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.

Tags: python

💬 Comments (0)

No comments yet. Be the first to share your thoughts!