+ 9

Variable scope in Python?

I want to change a variable using a function, but I get the error: local variable referenced before assignment. How can I use global variables inside functions?

27th Apr 2017, 1:14 PM
Supersebi3
Supersebi3 - avatar
6 odpowiedzi
+ 12
thing=0 def funky(): global thing print(thing) funky() # you can do multiple globals by using commas
27th Apr 2017, 1:16 PM
Ahri Fox
Ahri Fox - avatar
+ 10
ok thx
27th Apr 2017, 1:17 PM
Supersebi3
Supersebi3 - avatar
+ 9
@Tobi what do you mean with implementing a class? I am building something using the cmd module, and I didnt find a different way to do this
27th Apr 2017, 6:56 PM
Supersebi3
Supersebi3 - avatar
+ 8
I dont think that would work with the cmd module, or at least it would be unnecessary complicated
27th Apr 2017, 8:04 PM
Supersebi3
Supersebi3 - avatar
+ 1
In many cases I'd categorize what you want to do there as a code smell. Is there a reason you don't want to implement a class here?
27th Apr 2017, 5:09 PM
Tob
Tob - avatar
+ 1
You can define a class, which has your function as a method. This method will then be able to change attributes of an instance of that class.
27th Apr 2017, 8:02 PM
Tob
Tob - avatar