Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #42282
| References | <78680654-5cf5-435c-9fce-19d6f5c23360@googlegroups.com> |
|---|---|
| Date | 2013-03-29 14:23 -0700 |
| Subject | Re: Python class and variable issue(newby question!) |
| From | Benjamin Kaplan <benjamin.kaplan@case.edu> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3967.1364592579.2939.python-list@python.org> (permalink) |
On Fri, Mar 29, 2013 at 2:12 PM, Sam Berry <sambez_14@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).
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Python class and variable issue(newby question!) Sam Berry <sambez_14@hotmail.co.uk> - 2013-03-29 14:12 -0700
Re: Python class and variable issue(newby question!) Chris Angelico <rosuav@gmail.com> - 2013-03-30 08:24 +1100
Re: Python class and variable issue(newby question!) Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-03-29 22:51 +0000
Re: Python class and variable issue(newby question!) Chris Angelico <rosuav@gmail.com> - 2013-03-30 09:59 +1100
Re: Python class and variable issue(newby question!) Benjamin Kaplan <benjamin.kaplan@case.edu> - 2013-03-29 14:23 -0700
Re: Python class and variable issue(newby question!) Sam Berry <sambez_14@hotmail.co.uk> - 2013-03-29 15:17 -0700
Re: Python class and variable issue(newby question!) Chris Angelico <rosuav@gmail.com> - 2013-03-30 09:45 +1100
Re: Python class and variable issue(newby question!) Dave Angel <davea@davea.name> - 2013-03-29 18:56 -0400
csiph-web