Python super() behavior not dependable

前端 未结 5 1741
逝去的感伤
逝去的感伤 2021-02-01 13:37

For some reason, the super() method is not always behaving as expected, opting to return:

TypeError(\'super(type, obj): obj must be an instance or          


        
5条回答
  •  粉色の甜心
    2021-02-01 14:16

    I just had the same problem, running my code in jupyter notebook. I was using reload, so I restarted my kernel to follow up on Eduardo Ivanec's response to try and see if this was the problem. Then my code broke. I discovered my problem was related to several layers of inheritance, where the bottom layer was defined above the second bottom layer in the module.

    class MyClass1(object):
    '''example class 1'''
    
    class MyClass2(MyClass1):
    '''example class 2'''
        def __init__(self):
        super(MyClass2, self).__init__()
    
    class MyClass4(MyClass3):
    '''example class 4 - no __init__ definition'''
    
    class MyClass3(MyClass2):
    '''example class 3 - no __init__ definition'''
    

    When I moved MyClass4 underneath MyClass3, it fixed the problem.

    This is probably a rookie mistake, so it probably won't resolve the cause of the original problem above, but I thought I would post in case there are other rookies out there, like me, who are making the same mistake.

    (Apologies if my style is wrong, this is my first post on Stack Overflow. :))

提交回复
热议问题