Python super() behavior not dependable

走远了吗. 提交于 2019-12-02 18:45:51

Are you reloading modules somehow in the middle of things? If so, that may explain this error.

isinstance(self,DBAdminConnection) may become false after reloading modules because of the changes to memory references, apparently.

Edit: if you're running your web.py app under mod_wsgi, make sure you're disabling autoreload:

app = web.application(urls, globals(), autoreload=False)

If you are using reload() as part of your workflow, you apparently need to also use super(self.__class__, self).__init__ for inheritance initialization.

I suspect you will find this bug coincides with id(self.__class__) ==id(Retrieval) failing.

I'm not sure why the error is happening, but as an aid to debugging you could wrap the call to super in a try/except block and do a data dump when the exception is raised. Something like this:

class Retrieval(DBConnection.DBAdminConnection): 
    def __init__(self, username=None, password=None, unique_key=None):
        try:
            super(Retrieval,self).__init__()
        except TypeError, e:
            print "Failure initialising Retrieval --> self: %r"
            raise
        if username and password:
            self.username = username
            self.user.login(username,password, config.DATABASE)
            if self.user.error:
                raise UserLoginError(username)
        self.unique_key = unique_key

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. :))

I had the same error then i noticed that i had duplicate class (my mistake) within the same file.py. Error disappeared when i renamed the second class A to class B

#Just some example below, not real code
class A (object):

    def fun(self):
        super(A, self).fun()

class A (object): ##This second class with same name (A) caused the error

   def some_fun(self,x,y):
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!