[Tutor] Class variable & object variable

Damien damien.gouteux at gmail.com
Tue Jul 19 11:43:22 CEST 2005


I am a little bit confuse about class variable & object variable (Python 
I have:
class A(object):
    d = 50
    def __init__(self):
       print "Hello"

 >>> z = A()
 >>> A.d
(it's nice)
 >>> z.d

1) Why ?? d is not an object variable but a class variable !!! For the 
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).

It's very dangerous because:
 >>> z.d += 1
 >>> z.d
(now a object var is created called 'd')
 >>> z.__class__.d
(and if we want the 'old' class var, we need to put the '.__class__.d' 
to acces to the class)
Now the object var hides the class var. But the statement z.d+=1 is very 
confusing (at least, for me):
z.d(new object var) = z.d(old class var) + 1

Is it possible to have 'd' only for the class and not for instances of 
this class ?
and to have at (°) (z.d) an exception raised ?
(like "d is not defined for object z").

Thank you,


More information about the Tutor mailing list