TypeError: __init__() 得到了一个意外的关键字参数 'dir'

我尝试启动一个计时器来做一些文件归档工作。代码是这样的:


from threading import Timer


message_archive_dir = "achivedir"

message_archive_format = "zip"

archive_timer = Timer(86400, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)

archive_timer.start()



class messageachiver(object):

    def __init__(self, **kwargs):

            self.message_archive_dir = dir

            self.message_archive_format = fmt


    def archive(self):

            print("message_archive_dir is " + self.message_archive_dir)

            print("message_archive_format is " + self.message_archive_format)

            print("Archiving trade messages")

我收到以下错误:


Traceback (most recent call last):

  File "sa_listener.py", line 43, in <module>

    archive_timer = Timer(archive_interval, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format)

TypeError: __init__() got an unexpected keyword argument 'dir'

我不确定为什么 _ init _ 不接受 **kwargs。


阿波罗的战车
浏览 189回答 1
1回答

蛊毒传说

这个特定的初始化错误是因为您将多个变量传递给计时器类。在这一行中: Timer(86400, messageachiver.archive, dir = message_archive_dir, fmt = message_archive_format) 您将存档函数、dir 变量和 fmt 变量传递给 TIMER 而不是传递给 messageachiver 类。Timer 没有 dir 和 fmt 的命名变量。所以这条线应该是Timer(86400, messageachiver.archive)不过,这只能部分解决您的问题。因为您实际上从未使用需要它们拥有的变量来初始化类。所以在你调用定时器之前,你需要通过添加来初始化类messageachivermymessageachiver = messageachiver(dir = message_archive_dir, fmt = message_archive_format)在尝试初始化它之前,您还需要放置类定义。最终代码:from threading import Timerclass messageachiver(object):&nbsp; &nbsp; def __init__(self, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.message_archive_dir = kwargs['dir']&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.message_archive_format = kwargs['fmt']&nbsp; &nbsp; def archive(self):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("message_archive_dir is " + self.message_archive_dir)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("message_archive_format is " + self.message_archive_format)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Archiving trade messages")message_archive_dir = "achivedir"message_archive_format = "zip"mymessageachiver = messageachiver(dir = message_archive_dir, fmt = message_archive_format)# That's a huge wait time, try something like 10 for a smaller wait during testing.archive_timer = Timer(86400, mymessageachiver.archive)&nbsp;archive_timer.start()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python