Python - 2 个参数而不是一个?

Python - 2 arguments instead of one?

Python代码:

class Importer:
    from importlib import __import__, reload
    from sys import modules

    libname = ""
    import_count = 0
    module = None

    def __init__(self, name):
        self.libname = name
        self.import_count = 0

    def importm(self):
        if self.libname not in self.modules:
            self.module = __import__(self.libname)
        else:
            print("must reload")
            self.module = self.reload(self.module)
        self.import_count += 1

# test out Importer

importer = Importer("module")

importer.importm() # prints Hello
importer.importm() # prints Hello
importer.importm() # prints Hello (again)
print(importer.import_count)

上面的Python(3.8.1)代码在OnlineGDB,如果你运行,会报错:

TypeError: reload() takes 1 positional argument but 2 were given

当我打开 Python 中的 importlib 库时,我看到了这个:


# ... (previous code; unnecessary)

_RELOADING = {}


def reload(module): ## this is where reload is defined (one argument)
    """Reload the module and return it.

    The module must have been successfully imported before.

    """
    if not module or not isinstance(module, types.ModuleType): ## check for type of module
        raise TypeError("reload() argument must be a module")
    try:
        name = module.__spec__.name
    except AttributeError:
        name = module.__name__

    if sys.modules.get(name) is not module: ## other code you (probably) don't have to care about
        msg = "module {} not in sys.modules"
        raise ImportError(msg.format(name), name=name)
    if name in _RELOADING:
        return _RELOADING[name]
    _RELOADING[name] = module
    try:
        parent_name = name.rpartition('.')[0]
        if parent_name:
            try:
                parent = sys.modules[parent_name]
            except KeyError:
                msg = "parent {!r} not in sys.modules"
                raise ImportError(msg.format(parent_name),
                                  name=parent_name) from None
            else:
                pkgpath = parent.__path__
        else:
            pkgpath = None
        target = module
        spec = module.__spec__ = _bootstrap._find_spec(name, pkgpath, target)
        if spec is None:
            raise ModuleNotFoundError(f"spec not found for the module {name!r}", name=name)
        _bootstrap._exec(spec, module)
        # The module may have replaced itself in sys.modules!
        return sys.modules[name]
    finally:
        try:
            del _RELOADING[name]
        except KeyError:
            pass

# ... (After code; unnecessary)

所有双标签 (##) 评论都是我的

很明显 reload 确实有 1 个参数,它检查该参数是否是一个模块。在 the OGDB (OnineGDB) code 中,我只传递一个参数(很确定)并且它是模块类型(很可能)。如果我删除该参数(您可以编辑 OGDB),它会给出:

TypeError: reload() argument must be module

因此,出于某种原因,Python 一直认为我的论点比实际多了一个。我让它工作的唯一方法是编辑 importlib 文件,使 reload 有两个参数(不是一个好主意)。

我尝试了 运行ning PDB,但没有帮助。

任何人都可以发现任何明显错误的地方,比如实际上有两个论点吗?

import mymodule

reload(mymodule)

它是如何工作的...我不确定你的问题是来自上面那面大文字墙,这通常用于将状态重置为初始状态

mymodule.py

x = 5

main.py

from importlib import reload # in py2 you did not need to import it
import mymodule
print(mymodule.x) # 5
mymodule.x = 8
print(mymodule.x) # 8
reload(mymodule)
print(mymodule.x) # 5 again

我需要做的是将 import 放在 class 之外以使其正常工作。这里是the new OGDB. Credits to 。代码如下:

from importlib import __import__, reload
from sys import modules

class Importer:
    libname = ""
    import_count = 0
    module = None

    def __init__(self, name):
        self.libname = name
        self.import_count = 0

    def importm(self):
        if self.libname not in modules:
            self.module = __import__(self.libname)
        else:
            print("must reload")
            self.module = reload(self.module)
        self.import_count += 1

# test out Importer

importer = Importer("module")

importer.importm() # prints Hello
importer.importm() # prints Hello
importer.importm() # prints Hello (again)
print(importer.import_count)

您遇到问题是因为您正在调用 self.reload(self.module),这实际上等同于调用 reload(self, self.module)。要查看此内容,请尝试 运行 以下操作:

class Example:
    def some_method(*args):
        print(args)
    def some_other_method(self):
        self.some_method(1)

an_example = Example()
example.some_other_method()

尽管我们只将一个参数传递给 some_methodsome_method 没有 self 参数。

最好在您的 importm 方法中导入 reload 方法(或完全在 class 之外!),如下所示:

    def importm(self):
        from importlib import __import__, reload
        if self.libname not in self.modules:
            self.module = __import__(self.libname)
        else:
            print("must reload")
            self.module = reload(self.module)
        self.import_count += 1