【问题标题】:refering to instance of a class from its metaclass python从它的元类python引用一个类的实例
【发布时间】: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


【解决方案1】:

super().__call__() 返回新创建的实例 - 你必须将此值保存在一个变量中,使用 t 表示任何你想要的值并返回它。

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


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

【讨论】:

    猜你喜欢
    • 2015-06-10
    • 1970-01-01
    • 2011-12-02
    • 2021-11-19
    • 2023-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    相关资源
    最近更新 更多