(Jul-02-2017, 08:56 AM)Skaperen Wrote: where do you put your functions?
def func1(foo, setting1, setting2):
foo.do_something(setting1, setting2)
#then calling later
func(foo, setting1, setting2)
#instead of
def func1():
foo.do_something(setting1, setting2)
# calls the method do_something of global foo and uses the agruments setting1 and setting2, which are also looked up global
Your problem with UnboundLocal was a different.
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:
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.
from tkinter import Tk, Button
root = Tk()
def callback():
root.destroy()
Button(root, text='Quit', command=callback).pack()
root.mainloop()
better is:
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:
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