Skip to content
Quantoros

How can I overload constructors (or methods) in Python?

PythonLevel: Intermediate

How can I overload constructors (or methods) in Python?

Hints
  • Identify object types, mutability and execution order.
  • Trace a minimal example: which values and references change?

Answer

This answer actually applies to all methods, but the question usually comes up first in the context of constructors.

In C++ you’d write

class C {
    C() { cout << "No arguments\n"; }
    C(int i) { cout << "Argument is " << i << "\n"; }
}

In Python you have to write a single constructor that catches all cases using default arguments. For example:

class C:
    def __init__(self, i=None):
        if i is None:
            print("No arguments")
        else:
            print("Argument is", i)

This is not entirely equivalent, but close enough in practice.

You could also try a variable-length argument list, e.g.

def __init__(self, *args):
    ...

The same approach works for all method definitions.

Source and licence: Python 3.14.0 Programming FAQ — Python Software Foundation · PSF-2.0

Related questions