关于python:python-接收的参数比传递的多?

Python - Receiving more arguments than passing?

我正在学习python和gtk,所以我试图用cairo在屏幕上用鼠标绘制一个矩形(我只是设法在不使用鼠标的情况下绘制了一个矩形)。

然而,奇怪的事情发生了,因为我收到的争论比我传递的要多。这怎么可能?

绘制矩形-方法定义:

1
2
3
4
5
6
def draw_rectangle (self, widget, start_x_cood, start_y_cood, ending_x_cood, ending_y_cood):
    print ("draw_retangle")
    cr = cairo.Context ()
    cr.set_source_rgba(1, 1, 1, 1)
    cr.rectangle(start_x_cood, start_y_cood, ending_x_cood, ending_y_cood)
    cr.fill()

调用draw_rectangle的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def on_motion_notify_event (self, widget, event):
        print("on_motion_notify_event")
        if event.is_hint:
            x, y, state = event.window.get_pointer()
        else:
            x = event.x
            y = event.y
            state = event.state

        if self.firstClick :
            self.ending_x_cood = x
            self.ending_y_cood = y
            self.draw_rectangle(self, widget, self.start_x_cood, self.start_y_cood, self.ending_x_cood, self.ending_y_cood)

        return True

这给了我以下错误:

on_motion_notify_event
Traceback (most recent call last):
File"gui2.py", line 56, in on_motion_notify_event
self.draw_rectangle(self, widget, self.start_x_cood, self.start_y_cood, self.ending_x_cood, self.ending_y_cood)
TypeError: draw_rectangle() takes exactly 6 arguments (7 given)
on_motion_notify_event
Traceback (most recent call last):
File"gui2.py", line 56, in on_motion_notify_event
self.draw_rectangle(self, widget, self.start_x_cood, self.start_y_cood, self.ending_x_cood, self.ending_y_cood)
TypeError: draw_rectangle() takes exactly 6 arguments (7 given)

第七个论点是从哪里来的?我的搜索结果让我找到了"args"和"kwargs",但没什么意义。

我在这里上传了一个可运行的代码版本


python将self传递给您的实例方法,因此:

1
self.draw_rectangle(self, widget, self.start_x_cood, self.start_y_cood, self.ending_x_cood, self.ending_y_cood)

实际上有两次通过了self。你想要:

1
self.draw_rectangle(widget, self.start_x_cood, self.start_y_cood, self.ending_x_cood, self.ending_y_cood)