Variable scope within a class

G

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

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.
 
G

Gerrit Holl

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.
 
N

Nuff Said

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,781
Messages
2,569,615
Members
45,295
Latest member
EmilG1510

Latest Threads

Top