Static variable vs Class variable

minkoo.seo at gmail.com minkoo.seo at gmail.com
Tue Oct 9 12:16:12 EDT 2007


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?

Thanks.
- Minkoo




More information about the Python-list mailing list