类型错误:方法需要2个参数(给定3个)

0 投票
1 回答
1434 浏览
提问于 2025-04-17 22:32

我正在尝试写一个程序,用来监控USB驱动器的连接,使用的是pyudev库。以下是我的代码:

def __init__(self):
    self.window = gtk.Window()
    self.window.set_default_size(300, 300)

    self.vbox= gtk.VBox(False, 5)
    label = gtk.Label("Please plug the device")

    context = Context()
    monitor = Monitor.from_netlink(context)
    monitor.filter_by(subsystem='block',device_type='disk')
    observer = GUDevMonitorObserver(monitor)
    observer.connect("device-added",self.device_connected)
    monitor.start()

    self.vbox.pack_start(label)
    self.window.add(self.vbox)

    self.window.show_all()

def device_connected(self, device):
    self.window.remove(self.vbox)
    label = gtk.Label('{0!r} added'.format(device))
    self.vbox.pack_end(label)
    self.window.add(self.vbox)

这里是错误信息:

vineet@vineet:~/Documents/Project$ python project.py
TypeError: device_connected() takes exactly 2 arguments (3 given)
TypeError: device_connected() takes exactly 2 arguments (3 given)

请帮我解决这个问题。

我在尝试使用文档页面上提供的代码片段,链接在这里:docs。你会注意到,device_connected这个方法需要两个参数 - device_connected(observer, device),但是我的代码在这种情况下也不工作,还是返回同样的错误。我在想,这个方法到底是怎么工作的呢?难道每个类的方法不应该都有self作为参数吗?

1 个回答

0

文档里没有说明这些是类的方法,而是这个类发送的信号。(实际上,文档中使用的名称是“device-added”,这甚至不是一个有效的Python函数名。)

这个函数应该是一个独立的函数,你需要把它注册为这个信号的监听器。你可以在页面顶部的代码示例中看到如何将你的信号连接到观察者的例子。

撰写回答