Python class multiple constructors

Question:

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?

Asked By: Some Name

||

Answers:

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".

Answered By: gog
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.