从它的元类 python 中引用一个类的实例

问题描述

有没有办法在每次创建实例时从类的元类中引用类的实例?为此,我想我应该在元类中使用 dunder _call_ 方法

我有以下代码

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()

另外,为什么当我在元类中实现 __call__ 方法时,我的类的所有创建实例都变成了 nonetype 但是当覆盖 __call__ 时我使用了 super().__call__()? 例如 a4.test() 返回 AttributeError: 'nonetype' object has no attribute 'test'

解决方法

新创建的实例由 super().__call__() 返回 - 您必须将此值保留在变量中,使用 t 为您想要的任何东西并返回它。

否则,如果元类 __call__ 没有 return 语句,所有实例都会被立即取消引用和销毁,并且尝试创建实例的代码只会得到 None


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