Categories
Python Answers

How to implement multiple constructors with Python?

Spread the love

Sometimes, we want to implement multiple constructors with Python.

In this article, we’ll look at how to implement multiple constructors with Python.

How to implement multiple constructors with Python?

To implement multiple constructors with Python, we can add class methods into our class that calls the constructor.

For instance, we write

class Cheese(object):
    def __init__(self, num_holes=0):
        self.number_of_holes = num_holes

    @classmethod
    def random(cls):
        return cls(randint(0, 100))

    @classmethod
    def slightly_holey(cls):
        return cls(randint(0, 33))

    @classmethod
    def very_holey(cls):
        return cls(randint(66, 100))

gouda = Cheese()
havarti = Cheese.random()

to create the Cheese class with the __init__ method.

Then we can create static methods that calls __init__ with different arguments.

Next, we have

gouda = Cheese()
havarti = Cheese.random()

to use the different methods to create Cheese objects.

Conclusion

To implement multiple constructors with Python, we can add class methods into our class that calls the constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *