Is it possible in Python to do several constructors with a different number of arguments in the same class?

class a: def __init__(self,b): pass def __init__(self): pass 

In this case, you can create instances of the class only with the second constructor, while writing x = a (42) will cause an error.

    4 answers 4

    In short, NO.

    For more details, see the discussion HERE . There and solutions are such as the use of optional or key arguments.

      In Python, overloading of functions (and the constructor, in fact, is a function) is not in principle. In your case, the second constructor is always called, because the def instruction means "create a function object and assign this object to the written name", that is, first you assign the name __init__ one function (with the parameter b ), and then the same name - another function , already without parameter b .

      The behavior you are seeking can be obtained using the default parameters, for example:

       def __init__(self, b=None): # Здесь лучше придумать что-то отличное от проверки на None # больше соответствующее вашей задаче. Возможно, вам просто подойдет # какое-то значение по умолчанию. if b is None: pass else: pass # ... a = a() # b будет равно None по умолчанию b = a(42) # b будет равно 42 

        another option

         def __init__(self, *args, **kwargs): p = kwargs.get('name','trololo') 
        • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky

        and not easier to do this:

         class Troll(): def __init__(self, name='trololo', size=42) # ...... a = Troll() # а тут тролль по умолчанию - trololol, 42 b = Troll('ololol', 12) # тут у нас получиться маленький тролль с ником ололо