草庐IT

python - autoreload and package causing TypeError : super(type, obj): obj 必须是类型的实例或子类型

coder 2023-08-14 原文

我有 python 代码跨越几个文件,为了方便我打包了这些文件,最后在 my_package 目录下有以下 3 个文件:

__init__.py

内容:

from file1 import *
from file2 import *

file1.py 内容:

class Base(object):
    pass

file2.py 内容:

from file1 import Base 
class Derived(Base):
    def __init__(self):
        return super(Derived, self).__init__()

然后我在 IPython 中执行:

>>>%autoreload 2
>>>import my_package
>>>t = my_package.Derived()

到目前为止一切顺利。 但后来我对 file2.py 进行了更改,比如添加一个虚拟属性。 现在当我执行时:

>>>t = my_package.Derived()
>>>      2 class Derived(Base):
>>>      3     def __init__(self):
>>>----> 4         return super(Derived, self).__init__()
>>>      5 
>>>      6 dumm = 'asdf'
>>>
>>>TypeError: super(type, obj): obj must be an instance or subtype of type

在我重新启动 IPython 控制台之前,这不会消失。为什么 autoreload 不能正确处理这个问题?如果我将 Base 和 Derived 放入单个模块文件而不是包中,一切正常。

最佳答案

在 Python 3 中,使用新的 super().__init__() 而不是 super(Derived, self).__init__() 解决了我的问题

关于python - autoreload and package causing TypeError : super(type, obj): obj 必须是类型的实例或子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32481508/

有关python - autoreload and package causing TypeError : super(type, obj): obj 必须是类型的实例或子类型的更多相关文章

随机推荐