Search code examples
python-3.xmetaclassmethod-call

refering to instance of a class from its metaclass python


Is there any way to refer to instance of a class from its metaclass every time an instance is created? I suppose I should use dunder _call_ method inside metaclass for that purpose.

I have the following code:

class meta(type):   
    def __call__(cls):
       super().__call__()
       #<--- want to get an object of A class here every time when instance of A class is created

class A(metaclass = meta):
    def __init__(self, c):
        self.c = 2

    def test(self):
        print('test called')
   
a1=A()
a2=A()
a3=A()

Also why when I implement __call__ method inside metaclass all created instances of my class became NoneType however when overring __call__ I used super().__call__()? For example a4.test() returns AttributeError: 'NoneType' object has no attribute 'test'


Solution

  • The newly created instance is returned by super().__call__() - you hav to keep this value in a variable, use t for whatever you want and return it.

    Otherwise, if the metaclass __call__ has no return statement, all instances are imediatelly de-referenced and destroyed, and the code trying to create instances just get None:

    
    class meta(type):   
        def __call__(cls):
           obj = super().__call__()
           # use obj as you see fit
           ...
           return obj