Skip to content

Method

In one line

A method is a function defined inside a class that operates on an instance of that class via self.

In simple words

A method is a function that belongs to a class. It is defined inside the class body and takes self as its first parameter, which refers to the instance the method is called on.

When you call obj.method(args), Python automatically passes obj as self. This lets the method access and modify the object's attributes. Methods can also return values, just like regular functions.

Special methods (dunder methods) have double underscores, like __init__ (constructor), __str__ (string representation), __len__ (length), and *__eq__ (equality comparison). These define how objects behave with built-in operations.

Example

python
class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        return self.balance

    def __str__(self):
        return f"Account(balance={self.balance})"

acct = BankAccount(100)
print(acct.deposit(50))  # 150
print(acct)              # Account(balance=150)

Methods are class functions using self. Special dunder methods like __str__ define built-in behavior.

Common confusions

  • Confused with: function

    The difference: A method is a function defined inside a class and called on an instance (obj.method()). A function is standalone. Methods have an implicit 'self' parameter; functions do not.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary