By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,772 Members | 906 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,772 IT Pros & Developers. It's quick & easy.

Variable scope within a class

P: n/a
How do I make a variable available to code *inside* my class in such a way
that it is available to all defs in the class? In my example below f is not
accessible within the showVars method.

class myClass:
f = [1,2,3]

def showVars ( self ):
print f # Error here as f does not exist

def main():
x = myClass()
print x.f
x.showVars()

if __name__ == "__main__":
main()
Thanks to anyone who can offer some guidance to a Python beginner!
Graham.

Jul 18 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
On Tue, 03 Feb 2004 10:11:43 +0000, Graham wrote:
How do I make a variable available to code *inside* my class in such a way
that it is available to all defs in the class? In my example below f is not
accessible within the showVars method.


It depends on whether you want to have a class variable or an instance
variable; looking at the following variation of your code should make
clear the difference:

class myClass:
f = [1, 2, 3]

def showVars(self):
print self.f
class myClass2:
def __init__(self):
self.f = ['a', 'b']

def showVars(self):
print self.f
print myClass.f

myc = myClass()
myClass.f = [4, 5, 6]
myc.showVars()

myc2 = myClass2()
myClass2.f = ['c', 'd'] # this f is created here!!!
print myClass2.f
myc2.showVars()
+++ OUTPUT +++

[1, 2, 3]
[4, 5, 6]
['c', 'd']
['a', 'b']
Remark: 'Normally', you want something like myClass2.

HTH / Nuff

Jul 18 '05 #2

P: n/a
Hi Graham,
How do I make a variable available to code *inside* my class in such a way
that it is available to all defs in the class? In my example below f is not
accessible within the showVars method.

class myClass:
f = [1,2,3]

def showVars ( self ):
print f # Error here as f does not exist


Since f is a class variable, it is also an instance variable. You can
either reach it by referring to the class or by referring to the
instance. The former can be done with 'self.__class__.f', the latter by
the simpler 'self.f'. The difference is that, if self.f changes, this is
true for only 1 instance of the class, while all share the same
self.__class__.f.

Gerrit.

--
PrePEP: Builtin path type
http://people.nl.linux.org/~gerrit/c.../pep-xxxx.html
Asperger's Syndrome - a personal approach:
http://people.nl.linux.org/~gerrit/english/

Jul 18 '05 #3

P: n/a
Thanks Gerrit and Nuff Said. Very helpful indeed.

Graham
Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.