descriptor problems

Gary Stephenson garys at ihug.com.au
Thu Sep 14 11:22:07 CEST 2006


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.

My attempts so far have led me to using a descriptor as follow, but it 
doesn't get me where I want to be:

class sharedClassVar(object):
    def __init__(self,x=None):
        print "creating"
        self.value = x
    def __get__(self,ob,cls):
        print "getting"
        return self.value
    def __set__(self,ob,x):
        print "setting"
        self.value = x


class A( object ):
    # install it like this I guess:
    cls2 = sharedClassVar(5)

class B( A ):
    pass

print A.cls2  # so far so good
o = A()
o2 = B()
print o.cls2  # ok
print o2.cls2  # ok
o.cls2 = 2
print B.cls2  # perfect
print o2.cls2  # ""
o2.cls2 = 3
print A.cls2  # ""
print o.cls2  # ""

# but I need to be able to update the value through the class
# how do I do it?
A.cls2 = 4     # whoops - we just overwrote the descriptor with an integer

A.cls2.__set__(None,4)     # AttributeError: 'int' object has no attribute 
'__set__'







More information about the Python-list mailing list