我定义了一个元类,它将名为“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)