我有一个程序,它使用python for windows扩展来控制鼠标。 我正在尝试创建一个调用类变量的函数(我认为这就是他们所谓的)。
无论如何,代码看起来像这样:
class Mouse:
def move_mouse(self, pos):
"""move the mouse to the specified coordinates"""
(x, y) = pos
old_pos = self.get_position()
x = x if (x != -1) else old_pos[0]
y = y if (y != -1) else old_pos[1]
self._do_event(self.MOUSEEVENTF_MOVE + self.MOUSEEVENTF_ABSOLUTE, x, y, 0, 0)
它被称为:
mouse = Mouse();
position = (3,5); #some coordinate (where the mouse is on the screen)
mouse.move_mouse(position);
我想知道我是否可以创建一个函数来更容易调用move_mouse()函数。我可以让它调用我之前定义的位置吗?我可以创建一些像这样的东西:
positions = {"0": (123,432), "1": (312,123)}
def move(x);
mouse.move(positions[str(x)]);
>>>move(0)
该功能应该继续移动到位置字典中的第一个条目。
我无法阻止它在运行时出错。有人知道它为什么不起作用吗?
答案 0 :(得分:1)
一种方法是预定义位置的类属性,然后当调用Mouse.move_mouse
时,它会尝试从该字典中检索pos
,假设它是一个密钥,或者如果它不是密钥则直接使用它:
class Mouse:
POSITIONS = {'home': (0, 0), ...}
def move_mouse(self, pos):
"""move the mouse to the specified coordinates"""
x, y = self.POSITIONS.get(pos, pos)
...
现在,mouse.move_mouse('home')
和mouse.move_mouse((0, 0))
都会产生相同的效果。