Home > Blockchain >  Python class multiple constructors
Python class multiple constructors

Time:10-18

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?

CodePudding user response:

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

  • Related