小编Woo*_*ang的帖子

在动态添加的方法中调用 super 的正确方法是什么?

我定义了一个元类,它将名为“test”的方法添加到创建的类中:

class FooMeta(type):
    
    def __new__(mcls, name, bases, attrs):
        def test(self):
            return super().test()
        attrs["test"] = test
        cls = type.__new__(mcls, name, bases, attrs)
        return cls
Run Code Online (Sandbox Code Playgroud)

然后我使用这个元类创建两个类

class A(metaclass=FooMeta):
    
    pass
      

class B(A):
    
    pass
Run Code Online (Sandbox Code Playgroud)

当我跑步时

a = A()
a.test()
Run Code Online (Sandbox Code Playgroud)

引发 TypeError 的位置super().test()

super(type, obj): obj must be an instance or subtype of type
Run Code Online (Sandbox Code Playgroud)

这意味着super()无法正确推断父类。如果我将super呼叫更改为

def __new__(mcls, name, bases, attrs):
    def test(self):
        return super(cls, self).test()
    attrs["test"] = test
    cls = type.__new__(mcls, name, bases, attrs)
    return cls
Run Code Online (Sandbox Code Playgroud)

那么引发的错误就变成:

AttributeError: 'super' …
Run Code Online (Sandbox Code Playgroud)

python oop metaclass super

4
推荐指数
1
解决办法
516
查看次数

标签 统计

metaclass ×1

oop ×1

python ×1

super ×1