Python super()行为不可靠

Tho*_*ood 41 python inheritance super superclass

出于某种原因,该super()方法并不总是按预期运行,选择返回:

TypeError('super(type, obj): obj must be an instance or subtype of type)'
Run Code Online (Sandbox Code Playgroud)

我理解错误的含义.我不明白为什么它会出现错误.这是破解的代码片段.系统中的所有对象都是新样式对象.

真正有趣的是,这个错误并不总是出现.我不知道是什么导致了它.该super()在方法Retrieval中传递Retrieval类,然后本身作为一个对象,它是,据我所知,究竟如何super()应该被调用.

有什么想法吗?

在文件DBConnection.py中:

class DBAdminConnection(object):
    def __init__(self):
        self.user = DBUserConnection().user 
        self.submissions = DBSubmissionConnection()
Run Code Online (Sandbox Code Playgroud)

在文件Retrieval.py中

class Retrieval(DBConnection.DBAdminConnection): 
    def __init__(self, username=None, password=None, unique_key=None):
        super(Retrieval,self).__init__()
        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
Run Code Online (Sandbox Code Playgroud)

Edu*_*nec 57

你是否正在以某种方式重新加载模块?如果是这样,那可以解释这个错误.

isinstance(self,DBAdminConnection) 显然,由于内存引用的更改,重新加载模块后可能会变为false.

编辑:如果您在mod_wsgi下运行web.py应用程序,请确保禁用自动加载:

app = web.application(urls, globals(), autoreload=False)
Run Code Online (Sandbox Code Playgroud)

  • 就像你说的那样发生在我身上,因为我在IPython中使用了`%load_ext autoreload%autoreload 2 (14认同)

小智 12

如果您使用reload()作为工作流的一部分,您显然也需要super(self.__class__, self).__init__用于继承初始化.

我怀疑你会发现这个错误与id(self.__class__) ==id(Retrieval)失败同时发生.

  • `super(self .__ class__,self)`总是错的.如果你进一步继承它,它将成为一个无限循环. (8认同)