ZetCode

Python methods

last modified November 29, 2026 Python 3.15

In this article we show how to define and use methods in Python classes.

A method is a function defined inside a class body. Most methods are instance methods: they are called on an object and receive that object as their first argument, conventionally named self. Through self, a method reads and changes the attributes of the object. Python also has class methods, which receive the class instead of an instance, and static methods, which receive neither.

Classes themselves are introduced in the object-oriented programming chapter of the Python tutorial.

The first method

The example defines a class with the __init__ method, which sets up a new object, and one ordinary method.

first_method.py
class Lamp:

    def __init__(self, room):
        self.room = room
        self.on = False

    def switch(self):
        self.on = not self.on
        state = "on" if self.on else "off"
        print(f"the {self.room} lamp is {state}")


lamp = Lamp("kitchen")
lamp.switch()
lamp.switch()

The switch method flips the on attribute of the lamp and reports the new state. It is called with the dot notation, lamp.switch(), and without arguments; Python passes the lamp itself as self. Every call works on the state stored in that one object.

$ python first_method.py
the kitchen lamp is on
the kitchen lamp is off

self and bound methods

The self parameter is not a keyword, just the first parameter of the function. The call obj.method() is a shortcut for Class.method(obj).

self_param.py
class Lamp:

    def __init__(self, room):
        self.room = room

    def describe(self):
        return f"lamp in the {self.room}"


desk = Lamp("study")
hall = Lamp("hall")

print(desk.describe())
print(Lamp.describe(hall))

method = desk.describe
print(type(method))
print(method.__self__ is desk, method.__func__ is Lamp.describe)
print(method())

Calling Lamp.describe(hall) through the class passes the object explicitly and gives the same result as hall.describe(). Accessing desk.describe without calling it returns a bound method: an object of type method that remembers both the function (__func__) and the instance (__self__). A bound method can be stored and called later, and it still works on the original lamp.

$ python self_param.py
lamp in the study
lamp in the hall
<class 'method'>
True True
lamp in the study

Methods that change state

Methods keep an object in a valid state. They change its attributes and reject operations that would break it. A method can call other methods of the same object through self.

account.py
class Account:

    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
        self.history = []

    def deposit(self, amount):
        self._check(amount)
        self.balance += amount
        self.history.append(f"+{amount}")

    def withdraw(self, amount):
        self._check(amount)
        if amount > self.balance:
            raise ValueError(f"insufficient funds: {self.balance}")
        self.balance -= amount
        self.history.append(f"-{amount}")

    def _check(self, amount):
        if amount <= 0:
            raise ValueError(f"amount must be positive: {amount}")


acc = Account("Jane", 100)
acc.deposit(50)
acc.withdraw(30)
print(acc.balance, acc.history)

try:
    acc.withdraw(500)
except ValueError as e:
    print("error:", e)

The deposit and withdraw methods update the balance and record each operation in the history. Both call the _check helper to validate the amount. The leading underscore marks _check as internal: it is meant to be used by the class, not by its users. The withdraw method refuses to overdraw the account by raising ValueError, so the balance and the history stay unchanged.

$ python account.py
120 ['+50', '-30']
error: insufficient funds: 120

Method chaining

A method that changes the object can return self. The caller can then call the next method directly on the result, which gives a compact, readable style for building up an object step by step.

chaining.py
class Query:

    def __init__(self, table):
        self.table = table
        self.conditions = []
        self.order = None

    def where(self, condition):
        self.conditions.append(condition)
        return self

    def order_by(self, column):
        self.order = column
        return self

    def build(self):
        sql = f"SELECT * FROM {self.table}"
        if self.conditions:
            sql += " WHERE " + " AND ".join(self.conditions)
        if self.order:
            sql += f" ORDER BY {self.order}"
        return sql


query = Query("books").where("year > 2000").where("pages < 400").order_by("title")
print(query.build())
print(Query("authors").build())

The where and order_by methods record their arguments and return the query object, so the calls can be chained in one expression. The build method returns a string instead and ends the chain. Methods that modify an object in place usually return None rather than self, as list.sort does; chaining is a deliberate design choice for builder classes.

$ python chaining.py
SELECT * FROM books WHERE year > 2000 AND pages < 400 ORDER BY title
SELECT * FROM authors

Class methods

A class method is defined with the @classmethod decorator. It receives the class as its first argument, conventionally named cls. The most common use is an alternative constructor, a method that creates an object from other data than __init__ accepts.

class_method.py
class Temperature:

    def __init__(self, celsius):
        self.celsius = celsius

    @classmethod
    def from_fahrenheit(cls, fahrenheit):
        return cls((fahrenheit - 32) * 5 / 9)

    @classmethod
    def parse(cls, text):
        value, unit = float(text[:-1]), text[-1].upper()
        if unit == "F":
            return cls.from_fahrenheit(value)
        return cls(value)

    def show(self):
        return f"{type(self).__name__}({self.celsius:.1f} °C)"


print(Temperature(21.5).show())
print(Temperature.from_fahrenheit(98.6).show())
print(Temperature.parse("212F").show(), Temperature.parse("-4c").show())

The from_fahrenheit method converts the value and calls cls to create the object. The parse method reads a string such as 212F and delegates to the other constructors. Both are called on the class, because no object exists yet. The show method uses type(self).__name__ to print the name of the actual class. See also Python classmethod.

$ python class_method.py
Temperature(21.5 °C)
Temperature(37.0 °C)
Temperature(100.0 °C) Temperature(-4.0 °C)

Class-level state

Attributes defined in the class body belong to the class and are shared by all instances. Class methods are a natural place to read them.

class_state.py
class Ticket:

    issued = 0

    def __init__(self, event):
        Ticket.issued += 1
        self.number = Ticket.issued
        self.event = event

    @classmethod
    def count(cls):
        return cls.issued

    def label(self):
        return f"ticket #{self.number} for {self.event}"


for event in ["concert", "concert", "theatre"]:
    print(Ticket(event).label())

print("issued:", Ticket.count())

The issued attribute counts the created tickets. The constructor increments it through the class name and gives each ticket its own number. Assigning through self.issued would create an instance attribute and leave the class counter at zero. The count class method reports the total without needing an instance.

$ python class_state.py
ticket #1 for concert
ticket #2 for concert
ticket #3 for theatre
issued: 3

Class methods in subclasses

Because a class method receives the class it is called on, an alternative constructor called on a subclass creates an object of the subclass. Static methods, defined with @staticmethod, receive no automatic argument at all.

subclass.py
class Temperature:

    def __init__(self, celsius):
        self.celsius = celsius

    @classmethod
    def from_fahrenheit(cls, fahrenheit):
        return cls((fahrenheit - 32) * 5 / 9)

    @staticmethod
    def is_valid(celsius):
        return celsius >= -273.15

    def show(self):
        return f"{type(self).__name__}({self.celsius:.1f} °C)"


class BodyTemperature(Temperature):

    def has_fever(self):
        return self.celsius >= 38.0


t = BodyTemperature.from_fahrenheit(101.3)
print(t.show(), t.has_fever())
print(Temperature.is_valid(-300), t.is_valid(36.6))

BodyTemperature inherits from_fahrenheit. When it is called on the subclass, cls is BodyTemperature, so the new object has the has_fever method. A hard-coded Temperature(...) call in the constructor would have returned the base class instead. The is_valid static method is a plain function placed in the class namespace; it can be called on the class or on an instance. Static methods are covered in Python static methods.

$ python subclass.py
BodyTemperature(38.5 °C) True
False True

Overriding methods

A subclass can define a method with the same name as a method of its base class. The method of the subclass overrides the inherited one. Python looks up methods on the class of the actual object, so even methods of the base class call the overriding versions.

overriding.py
class Shape:

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

    def area(self):
        return 0.0

    def describe(self):
        return f"{self.name} with area {self.area():.2f}"


class Circle(Shape):

    def __init__(self, radius):
        super().__init__("circle")
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius ** 2


class Square(Shape):

    def __init__(self, side):
        super().__init__("square")
        self.side = side

    def area(self):
        return self.side ** 2

    def describe(self):
        return super().describe() + f" and side {self.side}"


for shape in [Shape("point"), Circle(1.5), Square(2)]:
    print(shape.describe())

The describe method is defined only in Shape, but its call self.area() runs the area method of the actual object: the circle's formula for the circle and the square's for the square. The Square class also overrides describe and uses super() to extend the inherited version instead of replacing it. See also Python super.

$ python overriding.py
point with area 0.00
circle with area 7.07
square with area 4.00 and side 2

Private names

Python has no access modifiers. A single leading underscore is a convention for internal methods and attributes. Two leading underscores, without trailing ones, trigger name mangling: inside a class body, the name __count is rewritten to _Counter__count.

mangling.py
class Counter:

    def __init__(self):
        self.__count = 0

    def increment(self):
        self.__count += 1
        return self.__count

    def _reset(self):
        self.__count = 0


c = Counter()
c.increment()
print(c.increment())

c._reset()
print(c.increment())

print(vars(c))
try:
    print(c.__count)
except AttributeError as e:
    print("error:", e)

The _reset method can still be called from the outside; the underscore only tells the reader that it is not part of the public interface. The __count attribute is stored as _Counter__count, as the vars function shows, so c.__count outside the class fails. Name mangling is meant to prevent clashes with attributes of subclasses, not to hide data.

$ python mangling.py
2
1
{'_Counter__count': 1}
error: 'Counter' object has no attribute '__count'

Source

Classes in the Python tutorial, classmethod, staticmethod

In this article we have worked with Python methods: instance methods and self, bound methods, methods that change state, method chaining, class methods as alternative constructors, static methods, overriding with super, and private names. See also Python static methods, Python property decorator, and Python magic methods.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.