HOWTO · Python

How to Overload a Constructor in Python

This tutorial demonstrates how to overload a constructor in Python

On this page

Python does not select among several __init__ methods by matching their parameters. If a class defines __init__ more than once, the later definition replaces the earlier one, so only that definition is available when an instance is created. To support several ways to initialize an object, put the choices in one initializer, expose named factory methods, or give initializer parameters useful defaults.

What Constructor Overloading Means in Python

In languages with signature-based constructor overloading, the runtime can choose a constructor from its parameter types or count. Python does not do that for repeated __init__ definitions. A single __init__ can accept flexible arguments and make a deliberate choice, but that is dispatch inside one method, not native overloading. Keep the accepted forms explicit so callers can see which values the class supports.

Use *args to Dispatch on Argument Types or Counts

The *args parameter collects positional arguments into a tuple. You can inspect its length or the values’ types, then initialize the instance accordingly. Check that an argument exists before reading it, and decide what the class should do when an input form is unsupported. The following runnable example supports one integer or one string and reports the selected value.

Run this example:

class Greeting:
    def __init__(self, *args):
        if len(args) != 1:
            self.message = "Pass one integer or string"
        else:
            value = args[0]
            if isinstance(value, int):
                self.message = str(value)
            elif isinstance(value, str):
                self.message = "Hello from " + value
            else:
                self.message = "Pass an integer or string"


print(Greeting("Delft").message)

Checking the count before accessing args[0] handles a call with no positional arguments safely. The count check also rejects extra arguments. In Python, bool is a subclass of int, so isinstance(True, int) is true; use an exact type check if booleans should not be accepted as integers.

A count-based choice is useful when each positional count has a clear meaning. This initializer supports exactly zero, one, or two arguments: no arguments select the default range, one argument supplies its stop, and two supply its start and stop. Any other count receives a clear message. Each branch checks the count before reading from args, so neither the zero-argument nor unsupported-count path indexes a missing value.

Run this example:

class RangeSpec:
    def __init__(self, *args):
        if len(args) == 0:
            self.start, self.stop = 0, 10
        elif len(args) == 1:
            self.start, self.stop = 0, args[0]
        elif len(args) == 2:
            self.start, self.stop = args
        else:
            self.start, self.stop = None, None
            self.message = "Pass zero, one, or two values"

    def describe(self):
        if self.start is None:
            return self.message
        return f"Range from {self.start} to {self.stop}"


for spec in (RangeSpec(), RangeSpec(5), RangeSpec(2, 5), RangeSpec(1, 2, 3)):
    print(spec.describe())

The four calls exercise all supported counts and one count beyond the supported range. For a larger set of forms, prefer named parameters or factory methods so callers do not need to remember what each positional count means.

Use @classmethod Factory Methods as Alternative Constructors

A @classmethod receives the class as its first argument, conventionally named cls. A factory method can transform another representation into the values required by the regular initializer, then return cls(...). This creates an instance and also works naturally with subclasses because cls refers to the class through which the method was called. Factory methods are named construction paths; they do not add overloads to __init__.

Run this example:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    @classmethod
    def from_pair(cls, pair):
        return cls(pair[0], pair[1])


point = Point.from_pair((3, 4))
print(point.x, point.y)

Use separate factories when the input formats have meaningful names, such as from_file, from_row, or from_coordinates. Validate or normalize data in the factory when that responsibility belongs to the conversion. Keep the main initializer as the single place that establishes the object’s required state.

Use Default Arguments for Optional Initialization Patterns

Defaults work well when parameters are genuinely optional and their meaning stays clear. They let callers omit values without adding dispatch logic. Prefer immutable defaults such as numbers, strings, or None; a mutable value like a list should usually be created inside the method so instances do not share it accidentally.

Run this example:

class Profile:
    def __init__(self, name="Guest", score=0):
        self.name = name
        self.score = score


for profile in (Profile(), Profile("Mina"), Profile("Mina", 7)):
    print(profile.name, profile.score)

Here callers can provide neither optional value, just a name, or both values. Defaults are less suitable when omission has several distinct meanings, when parameters depend on one another, or when many positional combinations become hard to remember. In those cases, keyword-only parameters or named factory methods can make calls clearer.

Choose the Right Constructor Pattern

Use defaults for a small set of ordinary optional values. Use a factory method when construction begins from a different representation or when the creation path deserves a descriptive name. Use *args dispatch only when a compact, stable set of positional forms is part of the intended API; validate counts and types before using the values. For complex validation, explicit branches and helpful error messages are easier to maintain than clever type tricks.

These techniques can be combined: factories may validate and then call the same initializer, while defaults handle optional fields. Choose the simplest interface that makes valid calls obvious and unsupported calls predictable. The essential rule is that Python has one effective __init__ definition per class; flexibility comes from the logic and named alternatives you provide around it.