【发布时间】:2021-09-13 21:49:21
【问题描述】:
有什么方法可以在每次创建实例时从其元类中引用一个类的实例?我想我应该为此在元类中使用 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'
【问题讨论】:
-
当然,因为你的
__call__方法返回None
标签: python-3.x metaclass method-call