Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is a method in Python

Understanding Methods in Python

When you're starting out with programming, you might find yourself surrounded by a sea of unfamiliar terms. One of these terms is "method." In the simplest sense, a method in Python is like a tool that performs a specific task. It's like having a Swiss Army knife where each tool has its own unique function. In Python, these tools – or methods – are attached to objects and they help us manipulate or interact with those objects in various ways.

Methods: The Basics

Imagine you have a robot that can perform certain tasks for you. If you want the robot to move forward, you might give it a command like move_forward(). In Python, if you have an object, a method would be a command that tells the object to perform a certain action.

Let's take a real example. Strings in Python are sequences of characters, and they come with a set of methods that you can use to work with them. For instance, there's a method called upper() that converts all the characters in a string to uppercase. Here's how you would use it:

greeting = "hello, world"
print(greeting.upper())  # Output: HELLO, WORLD

In this example, upper() is the method, and greeting is the object (a string in this case) that the method is being called on.

Defining Your Own Methods

While Python provides a variety of built-in methods, you'll often want to create your own. These user-defined methods are like writing your own set of instructions for the robot. In Python, you define a method using the def keyword, followed by the method name and a set of parentheses.

Here's a simple example of defining and using a method:

def say_hello(name):
    return f"Hello, {name}!"

print(say_hello("Alice"))  # Output: Hello, Alice!

In the say_hello method, name is what we call a parameter – it's like a placeholder for the actual value you want to use when you call the method.

The self Parameter: A Special Case

When defining methods for a class (a blueprint for creating objects), there's a special first parameter that you'll often see: self. This parameter refers to the instance of the class on which the method is being called. It's how the method knows which specific object it's working with.

Let's see how this works with a class called Dog:

class Dog:
    def __init__(self, name): = name

    def bark(self):
        return f"{} says woof!"

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

Here, __init__ is a special method called a constructor, which sets up the object when it's created. The bark method uses self to access the name of the dog instance and returns a string with the dog's bark.

Methods vs Functions: Clearing Up the Confusion

You might hear the terms "method" and "function" used interchangeably, but there's a distinction. A function is a piece of code that you can call by name anywhere in your code, and it operates independently. A method, on the other hand, is attached to an object and can only be called in the context of that object.

Think of a function as a standalone appliance in your home, like a toaster. You can use it on its own to toast bread. A method is more like the ice maker in your fridge – it's part of the fridge and relies on the fridge to function.

Here's a quick comparison:

# Function
def add_numbers(a, b):
    return a + b

# Method
class Calculator:
    def add(self, a, b):
        return a + b

# Using the function
result_function = add_numbers(3, 4)  # Output: 7

# Using the method
my_calculator = Calculator()
result_method = my_calculator.add(3, 4)  # Output: 7

Methods Can Also Modify Objects

Some methods don't just perform an action or return a value; they actually change the object they're called on. These are known as "mutator" methods or, more commonly, "mutating methods."

For example, lists in Python have a method called append() that adds an item to the end of the list. When you call this method, you're changing the original list:

my_list = [1, 2, 3]
print(my_list)  # Output: [1, 2, 3, 4]

After calling append(), the my_list object has been modified to include the new element.

Intuition and Analogies

To help solidify your understanding of methods, let's use an analogy. Imagine a book as an object. This book has certain methods associated with it, such as open(), turn_page(), and close(). These methods are actions you can perform on the book.

In Python, if the book were an object, you might have code like this:

class Book:
    def open(self):
        print("Opening the book.")

    def turn_page(self):
        print("Turning the page.")

    def close(self):
        print("Closing the book.")

my_book = Book()

Conclusion: Embrace the Method to Your Madness

As you continue your journey into the world of programming, you'll find that methods are your trusted companions. They're the verbs that give life to the nouns (objects) in your code, enabling you to tell a story with actions and interactions. Think of methods as the choreography in the dance of programming. Each step (method) is carefully designed to move the performance (program) forward in a meaningful way.

Remember, methods aren't just a tool for the code to execute; they're a way for you to express your intent and logic. By understanding and mastering methods, you're not just learning to code; you're learning to communicate with your computer in a language it understands. So go ahead, define your methods, call them with confidence, and watch as your code comes to life, one method at a time.