'Python overriding a method but using old version in it
I have a simple (I guess problem). Basically I want to use pynput mouse (pynput.mouse.Controller) to make my own class. So I did this:
from pynput.mouse import Controller as ms
from pynput.mouse import Button as btn
Button = btn
class Mouse(ms):
def __init__(self):
super().__init__()
def move(self, dx, dy):
curX, curY = self.position
print(curX, curY)
ms.move(dx - curX, dy - curY)
def move_click(self, x, y, button):
pass
The problem occurs in move method. It overrides a method from Controller which is move(self, dx, dy). I wanted to override it, cause it uses relative pixel coordinates, I want to use absolute coordinates.
So I do the calculation (dx - curX, dy - curY) and I want to pass those to the old version of move, so I don't call my own class' move, I call move from the imported Controller.
I wrote the code to check this:
from mouse import Mouse, Button
def main():
mouse = Mouse()
mouse.move(0, 0)
if __name__ == '__main__':
main()
The error I get is this:
C:\projects\python\test\mouse>python main.py
649 157
Traceback (most recent call last):
File "main.py", line 10, in <module>
main()
File "main.py", line 6, in main
mouse.move(0, 0)
File "C:\projects\python\test\mouse\mouse.py", line 14, in move
ms.move(dx - curX, dy - curY)
TypeError: move() missing 1 required positional argument: 'dy'
So what am I doing wrong? Should I change the way I import stuff, or maybe the thing I want to do is impossible?
Solution 1:[1]
I know this is old, but I'll parrot the responses from the comments above, and try to answer this question generally for anyone else that happens upon this.
If the parent class is called Parent, and you hope to override its method called foo(), this is a template of how to do that:
class Child(Parent):
def foo(*args, **kwargs):
return super().foo(*args, **kwargs)
Of course, this template as written would not behave any differently from never overriding foo() at all, but the point is that you'd want to change it to your specifications (e.g., include additional parameters, adjust return value, etc).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
