0

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'

1
  • Of course, because your __call__ method returns None Commented Jul 2, 2021 at 3:53

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.