[Tutor] Class variable & object variable

Alan G alan.gauld at freenet.co.uk
Tue Jul 19 14:29:03 CEST 2005

> class A(object):
>    d = 50
>    def __init__(self):
>       print "Hello"
> >>> z = A()
> >>> A.d
> 50
> >>> z.d
> 50
> 1) Why ?? d is not an object variable but a class variable !!!

Yes which means (definition of a class variable) that it's part of
every class and instance of the class.

> object z, d is not defined (in my mind, not for Python, as you can 
> see)(it's the same in Java :  all static variables can be accessed 
> from an object of the class or the class itself).

Thats what class attributes do, they are part of the class and
thus of instances of the class. After all, methods are defined at the
class level too and if they were not available to the instance
except by calling like:


it would get very tiresome.

> It's very dangerous because:
> >>> z.d += 1
> >>> z.d
> 51
> (now a object var is created called 'd')

And that I agree is confusing! THat is not standard class variable
behaviour and I personally don't like it. But there isn't any single
language I know where I like everything about it, so I live with it!
It's Guido's language, so he gets to choose how features work! :-)

> Is it possible to have 'd' only for the class and not for instances 
> of this class ?

I donl;t think so but it is possible that some of the new metaclass
stuff might allow that. Also you could probabnly use 
to do something similar.


Alan G.

More information about the Tutor mailing list