descriptor problems
Gary Stephenson
garys at ihug.com.au
Thu Sep 14 19:29:04 EDT 2006
"Peter Otten" <__peter__ at web.de> wrote in message
news:eeb8oq$79d$01$1 at news.t-online.com...
> Gary Stephenson wrote:
>
>> I want to define a class-level attribute that will be shared by all
>> subclasses. That is, I want this class, every subclass of this class,
>> every instance of this class and every instance of every subclass to be
>> able to
>> read and write to the _same_ slot/variable. But I can't figure out how
>> to
>> do it.
>
> class A:
> class __metaclass__(type):
> _shared = 42
> def get_shared(self):
> return self.__class__._shared
> def set_shared(self, value):
> print "%r --> %r" % (self._shared, value)
> self.__class__._shared = value
> shared = property(get_shared, set_shared)
>
> def get_shared(self):
> return self.__class__.shared
> def set_shared(self, value):
> self.__class__.shared = value
> shared = property(get_shared, set_shared)
>
> Does that what you want?
It certainly does! But I need to figure out how to package it up a bit more
elegantly. I'd prefer not to have to define a separate metaclass for each
class if I could avoid it. hmmm ..... The following is what I eventually
came up with, which is exactly what I was after:
class valueDescriptor(object):
def __init__(self,x=None):
self.value = x
def __get__(self,ob,cls=None):
return self.value
def __set__(self,ob,x):
self.value = x
class Ameta(type):
def createShared( cls, nm, initValue=None ):
o = valueDescriptor(initValue)
setattr( cls,nm, o )
setattr( cls.__class__,nm, o )
class A:
__metaclass__ = Ameta
class B( A ):
A.createShared("cls2",1)
Many thanks,
gary
More information about the Python-list
mailing list