将值插入listPython时出错

2024-10-04 03:18:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在列表中插入一个对象,但出现了一个错误:

    Archive.insertdoc(d)
TypeError: insertdoc() missing 1 required positional argument: 'd'

这是我的主要模块:

doc = Document(name, author, file)
Archive.insertdoc(doc)

Archive模块:

def __init__(self):
    self.listdoc = []

def insertdoc(self, d):
    self.listdoc.append(d)

Tags: 模块对象self列表docdef错误required
2条回答

看起来Archive.insertdoc是类Archive的实例方法。也就是说,它必须在Archive的实例上调用:

doc = Document(name, author, file)
archive = Archive()     # Make an instance of class Archive
archive.insertdoc(doc)  # Invoke the insertdoc method of that instance

您需要为Archive类创建一个实例;您正在访问unbound方法。你知道吗

这应该起作用:

archive = Archive()

doc = Document(name, author, file)
archive.insertdoc(doc)

假设您有:

class Archive():
    def __init__(self):
        self.listdoc = []

    def insertdoc(self, d):
        self.listdoc.append(d)

如果将两个函数放在模块级别,则不能在函数中有self引用并将其绑定到模块;函数不绑定到模块。你知道吗

如果您的存档应该是应用程序的全局存档,请在模块中创建Archive类的单个实例,并仅使用该实例。你知道吗

相关问题 更多 >