method

In Python, a method is a function that is associated with a particular object or class. Methods are typically defined within a class and can be called on objects of that class.

Methods define the behaviors and actions that an object of a class can perform. Methods can take arguments, including a reference to the instance of the class itself, typically named self, which allows them to access and modify the object’s attributes.

Methods are a fundamental part of object-oriented programming in Python. They enable encapsulation and the manipulation of an object’s state.

Example

Here’s a example of a method within a class:

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

    def speak(self):
        return f"{self.name} says Woof!"

# Usage
dog = Dog("Buddy")
print(dog.speak())  # Output: Buddy says Woof!

In this example, the .speak() method is defined within the Dog class and can be called on any instance of Dog. When dog.speak() is called, it returns the string "Buddy says Woof!", demonstrating how methods can interact with object attributes.

Tutorial

Python Classes: The Power of Object-Oriented Programming

In this tutorial, you'll learn how to create and use full-featured classes in your Python code. Classes provide a great way to solve complex programming problems by approaching them through models that represent real-world objects.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 21, 2025 • Reviewed by Dan Bader