Static variable vs Class variable
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Tue Oct 9 12:59:59 EDT 2007
On Tue, 09 Oct 2007 09:16:12 -0700, minkoo.seo at gmail.com wrote:
> I've got a question on the differences and how to define static and
> class variables.
First you have to define what you mean by "static".
> 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.
`classmethod`\s receive the class as first arguments, `staticmethod`\s are
just functions bound to the class object.
> 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:
Ask the guy what he means by "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.
No you define a class attribute that *is* bound to the class `Foo`.
> 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
Four!? Hard to believe.
>>>> 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?
There is no such thing as a "static" variable. Think of attributes that
are bound to objects. All dynamically.
What happens is: you bind a 1 to the attribute `Foo.a` in the `Foo` class
definition.
When you call `Child1.increment()` the class method will be called with
`Child1` as first argument. Now ``cls.a += 1`` is executed which is
somewhat like a short form of ``cls.a = cls.a + 1``. So this is reading
the attribute `a` from `Child1` and then bind the result to `Child1`.
`Child1` doesn't have an attribute `a`, so it is looked up in the parent
class. But the result is then bound to `Child1`. So you are reading from
`Foo` and writing to `Child1`. That's it.
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list