Python class and variable issue(newby question!)

Benjamin Kaplan benjamin.kaplan at case.edu
Fri Mar 29 22:23:13 CET 2013


On Fri, Mar 29, 2013 at 2:12 PM, Sam Berry <sambez_14 at hotmail.co.uk> wrote:
> Hey,
>
> Im new to object orientated programming and have an issue with using classes. Im using the kivy module, a GUI creator , so posting the actual code may confuse. But an example of what im trying to achieve is below
>
> class test()
>     s = 1
>
>     def test1()
>         global s
>         s = 2
>
>     def test2()
>         global s
>         s = 3
>
>     def test3()
>         global s
>         s = 4
>
>
> class test4()
>
>     def printing()
>         print test().s
>
> After been in the test()class  a choice of buttons allows the user to run either of the functions within it and sends us into the test4() class. Then another button runs printing().
>
> However printing() always prints 1, even if the variable has been changed. Im guessing because  print test().s  redefines the variable. May be a very simple to solve problem, but i cant figure it out.
>
> Any insights of how to get this working, or example code would be very helpful!
>
> Thanks, Sam
> --


There are three different namespaces here: global, class, and local.
You're assigning to the global s, which exists outside the class. Do
"print s" instead of "print test().s" and you'll see your changed
value of s. If you want to change the value of s inside the class,
it's called "test.s" (notice that there's no parenthesis- that's
because s here is an attribute of the test class, not each instance of
test. The same value will be shared by all instances of that class).



More information about the Python-list mailing list