Static variable vs Class variable
mccredie at gmail.com
Tue Oct 9 19:20:29 CEST 2007
On Oct 9, 9:16 am, "minkoo.... at gmail.com" <minkoo.... at gmail.com>
> I've got a question on the differences and how to define static and
> class variables. AFAIK, class methods are the ones which receives the
> class itself as an argument, while static methods are the one which
> runs statically with the defining class.
> Hence, my understanding is that static variables must be bound to the
> class defining the variables and shared by children of parent class
> where the variable is defined. But, please have a look at this code in
> which a guy told me that the variable a is static:
> >>> class Foo:
> a = 1
> def increment(cls):
> cls.a += 1
> print cls.a
> Here, I am defining variable a which, I believe is class variable,
> i.e., variable that is not bound to Foo itself. Rather, a is bound to
> the class which is accessing the variable. The code that corroborates
> this idea is as follows:
> >>> class Child1(Foo):
> >>> Child1.increment()
> >>> class Child2(Foo):
> >>> Child2.increment()
> This means that Child1 and Child2 does not share variable a which
> means that variable a is class variable rather than static variable.
> Could you please comment on this? Is a static or class variable?
> What's the most recent way of defining 'class' and 'static' variables?
In Python `a' is considered a class variable. By modifying `a' using a
class method though, you are essentially re-binding `a' to the class
that it is called from. So, it will be shared by multiple instances of
the same class, but not derivatives. The re-binding only occurs when
`increment' is called. This makes for some very confusing behavior.
I'm not aware of a way, in python, to explicitly specify a variable as
static. For the behavior I think you are looking for you just need to
modify it carefully. This can be done with a static, class or instance
method. Though, using a class method is kind of silly. I'm sure some
would argue that using an instance method is also silly.
a = 0
C.a += 1 # directly modify the variable on the base class that it is
# or you could use a static method, which is fine since the instance
isn't being used. This
# will also allow the method to be called without instantiating the
a = 0
C.a += 1
More information about the Python-list