Search code examples
pythonsupermetaclassabcsix

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.


Solution

  • 0-argument super uses the class in which the call actually appeared, but after @six.add_metaclass(ABCMeta), the class bound to the ChildClass name is a new class created by the decorator. 0-argument super is still using the original class.

    If you're going to use 0-argument super, which only works on Python 3, just use Python 3 metaclass syntax instead of six.