Variable scope within a class
Nuff Said
nuffsaid at phreaker.net
Tue Feb 3 05:48:36 EST 2004
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
More information about the Python-list
mailing list