Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python class multiple constructors

There is a class that I want to be constructed from a string in 2 different ways. Here is what I mean:

class ParsedString():

    def __init__(self, str):
         #parse string and init some fields

    def __init__2(self, str):
         #parse string in another way and init the same fields

In Java I would provide a private constructor with 2 static factory methods each of which define a way of parsing string and then call the private constructor.

What is the common way to solve such problem in Python?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just like in java:

class ParsedString():

    def __init__(self, x):
        print('init from', x)

    @classmethod
    def from_foo(cls, foo):
        return cls('foo' + foo)

    @classmethod
    def from_bar(cls, bar):
        return cls('bar' + bar)


one = ParsedString.from_foo('!')
two = ParsedString.from_bar('!')

docs: https://docs.python.org/3/library/functions.html?highlight=classmethod#classmethod

There’s no way, however, to make the constructor private. You can take measures, like a hidden parameter, to prevent it from being called directly, but that wouldn’t be considered "pythonic".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading