What is a clean, pythonic way to have multiple constructors in Python?

后端 未结 13 2338
醉梦人生
醉梦人生 2020-11-22 07:12

I can\'t find a definitive answer for this. As far as I know, you can\'t have multiple __init__ functions in a Python class. So how do I solve this problem?

13条回答
  •  眼角桃花
    2020-11-22 07:35

    One should definitely prefer the solutions already posted, but since no one mentioned this solution yet, I think it is worth mentioning for completeness.

    The @classmethod approach can be modified to provide an alternative constructor which does not invoke the default constructor (__init__). Instead, an instance is created using __new__.

    This could be used if the type of initialization cannot be selected based on the type of the constructor argument, and the constructors do not share code.

    Example:

    class MyClass(set):
    
        def __init__(self, filename):
            self._value = load_from_file(filename)
    
        @classmethod
        def from_somewhere(cls, somename):
            obj = cls.__new__(cls)  # Does not call __init__
            super(MyClass, obj).__init__()  # Don't forget to call any polymorphic base class initializers
            obj._value = load_from_somewhere(somename)
            return obj
    

提交回复
热议问题