(Jul-02-2017, 08:56 AM)Skaperen Wrote: where do you put your functions?
1 2 3 4 5 6 7 8 9 10 |
def func1(foo, setting1, setting2):
foo.do_something(setting1, setting2)
func(foo, setting1, setting2)
def func1():
foo.do_something(setting1, setting2)
|
Your problem with UnboundLocal was a different.
1 2 3 4 5 |
n = 0
def bar():
n = n + n
return n
|
With the first assignment of a name, the Python interpreter looks, if the name exists locally
(n + n)
. In this case, the answer is no.
It can't be assigned, because the expression looks up the name n and it doesn't exist as local variable.
Different example which works:
1 2 3 4 5 6 |
n = 10
def bar():
global n
n = n + n
return n
|
But this function has a side effect. It turns the global variable into 20.
The returning value is the same like the global value. Avoid this.
You'll see this very often in tutorials for tkinter.
1 2 3 4 5 6 7 8 9 |
from tkinter import Tk, Button
root = Tk()
def callback():
root.destroy()
Button(root, text = 'Quit' , command = callback).pack()
root.mainloop()
|
better is:
1 2 3 4 5 6 7 8 9 |
from tkinter import Tk, Button
root = Tk()
def callback(root):
root.destroy()
Button(root, text = 'Quit' , command = lambda : callback(root)).pack()
root.mainloop()
|
lamda: callback(root)
is an anonymous function. It's not called directly. It's called, when pressing the button.
A more elegant way without lamba:
1 2 3 4 5 6 7 8 9 10 |
from functools import partial
from tkinter import Tk, Button
root = Tk()
def callback(root):
root.destroy()
Button(root, text = 'Quit' , command = partial(callback, root)).pack()
root.mainloop()
|
https://docs.python.org/3.6/library/functools.html#functools.partial
https://docs.python.org/3/tutorial/contr...xpressions # in the example with lamda, it takes no arguments