Beginners question
Albert Hopkins
marduk at letterboxes.org
Fri Jul 17 22:13:24 EDT 2009
On Fri, 2009-07-17 at 21:42 -0400, Ronn Ross wrote:
> How do you define a global variable in a class.
I bit of a mix-up with words here. A variable can be a class variable
or a global variable (wrt the module).. not both.
> I tried this with do success:
> class ClassName:
> global_var = 1
>
> def some_methos():
> print global_var
>
> This doesn't work. What am I doing wrong?
You could have posted the error message... Two things are wrong here.
The first, if some_methos() is a method of ClassName then it should have
at least one parameter, which is the instance of the class (i.e.
"self"), so
def some_methos(self):
The second problem is that global_var is not local so you need to
specify the scope. You can either use
print ClassName.global_var
or
print self.global_var
I'm not sure which one is better though I prefer the former because it
makes it clearer to the reader that it's a class variable and not an
instance variable.
HTH,
-a
More information about the Python-list
mailing list