No history yet

Python Methods Overview

Three Kinds of Methods

In Python, when you define a function inside a class, it's called a method. But not all methods behave the same way. Depending on what they need to do, they can interact with the class and its objects in different ways. Let's explore the three types: instance, class, and static methods.

Instance Methods

Instance methods are the most common type of method you'll write. They operate on a specific object, or instance, of a class. This means they can access and modify the object's unique data.

Every instance method has a special first parameter, which by convention is named self. When you call a method on an object, Python automatically passes that object to the method as the self argument. This is how the method knows which specific object's data to work with.

class Dog:
    def __init__(self, name):
        self.name = name  # Instance-specific data

    # This is an instance method
    def speak(self):
        return f"{self.name} says woof!"

my_dog = Dog("Rex")
print(my_dog.speak()) # Output: Rex says woof!

In this example, speak() is an instance method. It uses self.name to access the name of the particular dog instance (my_dog) it was called on. If we created another dog, buddy = Dog("Buddy"), calling buddy.speak() would use Buddy's name, not Rex's.

Class Methods

Sometimes, a method needs to work with the class itself, rather than a specific instance. This is where class methods come in. Instead of taking self as the first parameter, they take cls, which represents the class.

To signal that a method is a class method, you use a special syntax called a decorator: @classmethod. Class methods can't access instance-specific data (like self.name), but they can access class-level data or call other class methods.

A common use for class methods is to create factory methods. These are methods that provide alternative ways to create instances of your class.

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    @classmethod
    def from_string(cls, book_string):
        # book_string is like "The Hobbit-J.R.R. Tolkien"
        title, author = book_string.split('-')
        return cls(title, author) # 'cls' creates an instance

book_one = Book.from_string("Dune-Frank Herbert")
print(book_one.title) # Output: Dune

Here, from_string is a class method. It's called on the Book class directly, not an instance. It takes a string, parses it, and then uses cls(title, author) to create a new Book instance. Using cls is like calling Book(...).

Static Methods

Finally, we have static methods. These are the simplest type. They don't receive any special first argument—no self and no cls. A static method is essentially a regular function that lives inside the class's namespace, usually because it has a logical connection to the class.

Static methods cannot access or modify class state or instance state. They are self-contained. You mark a method as static with the @staticmethod decorator.

class MathUtils:
    @staticmethod
    def add(x, y):
        return x + y

    @staticmethod
    def is_even(num):
        return num % 2 == 0

result = MathUtils.add(5, 10)
print(result) # Output: 15

print(MathUtils.is_even(4)) # Output: True

The MathUtils class groups related math functions. Since add and is_even don't need any information about a specific instance or the class itself, they are perfect candidates for static methods. You can call them directly from the class, just like a class method.

Quick Comparison

Here’s a simple breakdown of the key differences.

Method TypeFirst ParameterAccesses Instance Data?Accesses Class Data?
Instance MethodselfYesYes
Class MethodclsNoYes
Static MethodNoneNoNo

Choosing the right method type makes your code clearer and more organized. Most of the time you'll use instance methods, but knowing when to use class or static methods is a key part of effective object-oriented programming.

Now, let's test your understanding of these concepts.