Global variables within classes.
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Nov 30 08:10:00 EST 2007
Kevac Marko a écrit :
> On Nov 10, 8:39 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
>> Don't think so. It's a surprise for many but then class attributes are
>> not that common in code or they even use this "gotcha" for
>> immutable default values. As long a the value isn't changed the default
>> value is just referenced from the class then and not every instance.
>>
>
> When changing default value, is there any way to change class
> attribute and all referenced attributes too?
>
> class M:
> name = u"Marko"
>
> a, b = M(), M()
> a.name = u"Kevac"
> print M.name, a.name, b.name
> -> Marko Kevac Marko
>
> Is there any way to get here -> Kevac Kevac Kevac ?
class ClassAttribute(object):
"""
If you dont understand this code, google for
+python +descriptor +protocol
"""
def __init__(self, attrname, default=""):
self.attrname = attrname
self.default = default
def __get__(self, inst, cls):
return getattr(cls, self.attrname, self.default)
def __set__(self, inst, val):
setattr(type(inst), self.attrname, val)
class M(object):
name = ClassAttribute('_name', "Marko")
a, b = M(), M()
a.name = u"Kevac"
print M.name, a.name, b.name
HTH
More information about the Python-list
mailing list