gagsl-py2 at yahoo.com.ar
Fri Jul 17 23:34:39 EDT 2009
En Fri, 17 Jul 2009 22:42:43 -0300, Ronn Ross <ronn.ross at gmail.com>
> How do you define a global variable in a class. I tried this with do
> class ClassName:
> global_var = 1
> def some_method(self):
> print global_var
> This doesn't work. What am I doing wrong?
[some typos fixed]
In Python, a "variable" is just a name in a namespace that references
There are five possible namespaces here:
- The local namespace, that is, the namespace inside some_method. All
assigned-to names that appear inside the function (there is none in this
case) are in the local namespace. But you're not interested on these local
names, I presume, because you said "global"
- The global namespace: the namespace of the module containing the code
(NOT a "super-global" namespace shared by all modules). Names in this
namespace are "global" in the sense that all code in the same module can
reference them. But they're not restricted to any class, as you requested.
To use a global name in an expression, just write it. To assign a new
value to a global name, you must use the "global" statement if you're
inside a function (else, it's considered a local name, see above).
- The built-in namespace: like a super-global namespace, it is searched
last when looking for an unqualified name; by example, the "len" function.
For most purposes, you should consider the built-in namespace read-only.
- The instance namespace: each object has its own namespace; you access
its names using dotted attributes: obj.name -- or self.attribute when
inside a method. The instance namespace is not determined by the object
type or class; any object may contain any attribute name (in general).
- The class namespace: classes may contain attributes too (like any other
object, because classes are objects too). In your code above, you may use
ClassName.global_var to refer to such class attribute. To resolve a dotted
attribute name, Python searches the instance first -- and if no match is
found, then the class namespace is searched too: this way, class
attributes effectively are "default values" for instance attributes. Since
all existing instances of a certain class share the same class, this is
like a "shared attribute" between all instances (like "static members" in
other languages). Inside some_method above, you may use self.global_var or
ClassName.global_var -- but once you *assign* something to the instance
attribute (self.global_var = xxx), the class attribute is shadowed and you
may reference it using ClassName.global_var only.
More information about the Python-list