Python · Functions & Decorators

Function vs method

Mediumfunctionmethodoopself

Interview question

What is the difference between a function and a method in Python?

How to answer

The short answer

A function is a callable defined with def or lambda at module (or local) scope. A method is a function defined inside a class body and accessed through an instance or class; it is bound to that object.

  • Function: len(x), sorted(items), helper(a, b).
  • Method: items.append(x), text.upper(), MyClass.from_config(...).

Bound instance methods receive the instance as self automatically. Calling obj.method creates a bound method; Class.method(obj, ...) is the unbound/manual form.

Python
def greet(name):          # function
    return f"hi {name}"

class Greeter:
    def __init__(self, name):
        self.name = name

    def greet(self):      # instance method
        return f"hi {self.name}"

    @classmethod
    def default(cls):     # class method
        return cls("guest")

    @staticmethod
    def shout(msg):       # static method (no self/cls)
        return msg.upper()

print(greet("Asha"))
g = Greeter("Asha")
print(g.greet())
print(Greeter.greet(g))   # explicit self

Short version: Methods are functions attached to a class/type, usually operating on that type's data.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill