首页 > 解决方案 > Why python super() not working without parameters in ABCMETA class?

问题描述

I have a problem with understanding function super() behavior in abc.ABCMeta class in python3.6.

class ParentClass():
    def test():
        return 1
​
@six.add_metaclass(ABCMeta)
class ChildClass(ParentClass):
    def test(self):
        test_ = super().test
        test_ = 2
        return test_
​
a = ChildClass()
​
a.test()

Code failed with 'TypeError: super(type, obj): obj must be an instance or subtype of type'.

When I used super(ChildClass, self).test it worked correctly! Printing from ChildClass test function:

print(__class__)

print(type(__class__))

print(ChildClass)

print(type(ChildClass))

I get next output:

<class '__main__.ChildClass'>

<class 'type'>

<class '__main__.ChildClass'>

<class 'abc.ABCMeta'>

I feel that the reason in object initialization but I can't undersand this information with my current skills in OOP and Python OOP.

标签: pythonsupermetaclassabcsix

解决方案


0-argumentsuper使用实际出现调用的类,但在 之后@six.add_metaclass(ABCMeta),与名称绑定的ChildClass类是装饰器创建的新类。0 参数super仍在使用原始类。

如果您要使用 0-argument super,它只适用于 Python 3,只需使用 Python 3 元类语法而不是six.


推荐阅读