[Tutor] Class variable & object variable
Damien
damien.gouteux at gmail.com
Tue Jul 19 11:43:22 CEST 2005
Hi,
I am a little bit confuse about class variable & object variable (Python
2.4).
I have:
class A(object):
d = 50
def __init__(self):
print "Hello"
>>> z = A()
Hello
>>> A.d
50
(it's nice)
>>> z.d
50
(°)
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
51
(now a object var is created called 'd')
>>> z.__class__.d
50
(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,
Damien.
More information about the Tutor
mailing list