jeudi 3 février 2022

How to define methods and member variables in class defined with custom metaclass in python

I am defining a singleton class, and using that class as a metaclass to create new classes.

class Singleton(type):
    _lock: Lock = Lock()
    _instance = {}

    def __call__(cls, *args, **kwargs):
        with cls._lock:
            if cls not in cls._instance:
                _instance = super().__call__(*args, **kwargs)
                cls._instance[cls] = cls

        return cls._instance.get(cls)

and the new class is defined like below

class SomeClass(metaclass=Singleton):
    def __init__(self, some_list = []):
         self.some_list = some_list

    def add_to_list(self, a):
         self.some_list.append(a)


some_class = SomeClass()

I am not able to access some_list variable of some_class object. It throws invalid attribute error.

some_class.some_list

a_list = [1,2,4,5]
for l in a_list:
    some_class.add_to_list(l)

Also, I am not able to call add_to_list fn. It throws missing paramter "a" in the arguments.

Can some one help what I am missing in understanding of metaclass concept.

Aucun commentaire:

Enregistrer un commentaire