[Tutor] Class variable & object variable
damien.gouteux at gmail.com
Tue Jul 19 14:56:17 CEST 2005
thx for your quick (and complete) answers.
to Alan G :
I will try to see what setattr() and getattr() can do for me. I'm not
used to this stuff.
to Alex Nedelcu :
If I understand correctly :
There are two different references (A.d in the dict of the class A and
z.d in the dict of the object z) but on the same object, am I right ?
(with z = A())
Alan G a écrit :
>> class A(object):
>> d = 50
>> def __init__(self):
>> print "Hello"
>> >>> z = A()
>> >>> A.d
>> >>> z.d
>> 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
>> (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 getattr()/settatr()
> to do something similar.
> Alan G.
More information about the Tutor