1

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?

1
  • (it is not a constructor, but a initializer. Note that it receives self , so it must have already been constructed ) Commented Oct 25, 2022 at 17:11

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Looks like the solution works both for python 2 and python 3. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.