Avatar ·

Multiple constructors with different number of arguments

📁 Advanced Python Topics

Is it possible in Python to have multiple constructors with different number of arguments in one class?

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

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

Avatar ·

Here is a version that does not leak memory and supports wrapping multiple classes.

Metaclass:

import weakrefclass MyMeta(type):    def __init__(self, *args, **kwargs):        self.__instances = {}        super(MyMeta, self).__init__(*args, **kwargs)    def get_instances(self):        retu list(self.__instances.values())    def delete(self, id_instance):        
                            

Log in to leave an answer

Blogs