Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Use a predefined function with parameters
-
I have this code but it seems impossible for me to save the function to a variable with parameters and call it later on.
<pre>
from scene import *class MyScene (Scene):
def setup(self):
self.a = test(200,200)def draw(self): background(0, 0, 0) test(100,100) #how do I call self.a with its parameters
run(MyScene())
def test(x,y):
rect(x,y,20,20)</pre>
Test(100,100) works fine !
Re Peter -
There is a better answer but...
def test(x = 200, y = 200): return rect(x, y, 20, 20)
Do you want 'return' on that last line?
-
You can use <b>partial</b> from the <b>functools</b> library. Like this:<pre>
from scene import *
from functools import partialclass MyScene (Scene):
def setup(self):
self.a = partial(test, 200, 200)def draw(self): background(0, 0, 0) #test(100,100) self.a()
run(MyScene())
def test(x,y):
rect(x,y,20,20)</pre> -
Ohhh thanks, just what I was after :-)
Python has all these smart bits, but sometimes hard to find if you do not know what to search for. Like this one, the name does not tell exactly.Re Peter
-
I forgot to mention that you can also use python's <b>lambda</b> to accomplish this.<pre>from scene import *
class MyScene (Scene):
def setup(self):
self.a = lambda: test(200, 200)def draw(self): background(0, 0, 0) #test(100,100) self.a()
run(MyScene())
def test(x,y):
rect(x,y,20,20)</pre>