Static variable vs Class variable

Matimus mccredie at gmail.com
Tue Oct 9 13:20:29 EDT 2007


On Oct 9, 9:16 am, "minkoo.... at gmail.com" <minkoo.... at gmail.com>
wrote:
> Hi.
>
> 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
>         @classmethod
>         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):
>
>         pass
>
> >>> Child1.increment()
>
> 4
>
> >>> class Child2(Foo):
>
>         pass
>
> >>> Child2.increment()
>
> 4
>
> 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.

code:

class C(object):
 a = 0
 def inc(self):
  C.a += 1 # directly modify the variable on the base class that it is
attached to
  return C.a

# 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
class.

class C(object):
 a = 0
 @staticmethod
 def inc():
  C.a += 1
  return C.a

Matt




More information about the Python-list mailing list