On 7/31/06, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Colin J. Williams wrote: > > Andre Meyer wrote: > >> Hi all > >> > >> I am trying to understand the magic of Python's class variables and > >> tried the following code (see below). > >> > >> Just out of curiosity, I tried to define a property that provides > >> access to a seemingly instance variable which is in fact a class > >> variable. > > [...] > > I'm afraid there are too much problems with indentation in the posted > code to give any serious answer.
So, here we go again (plain formatting). The following code shows two versions of using class variables. The first one uses the __class__ attribute directly and works. The second one tries to hide the __class__ attibute with the help of a property, which does not work, because an assignment in the instance replaces the property with the assigned value. Any idea how the second version could be fixed with either a property and/or a decorator? thanks for your help André class Value(object): def __init__(self, i): self.i = i def work(self): return 'done', self.i print; print "*** Case A ***"; print class ClassA(object): v = None def __init__(self, value): print '-', self.v self.__class__.v = Value(value) print '+', self.__class__.v @classmethod def value1(self): print self.v.work() return self.v def value2(self): print self.__class__.v.work() return self.__class__.v va1 = ClassA(1) va2 = ClassA(2) print va1.value1() print va1.value2() print va1.v print va1.__class__.v print va1.v.work() print "*** Case B ***"; print class ClassB(object): def __set_v(self, v): self.__class__.__v = v def __get_v(self): return self.__class__.__v def __del_v(self): del self.__class__.__v # v = property(__get_v, __set_v, __del_v, 'make class variable') v = None def __init__(self, value): self.v = property(self.__get_v, self.__set_v, self.__del_v, 'make class variable') print '-', self.v self.v = Value(value) print '+', self.v @classmethod def value1(self): print self.v.work() return self.v def value2(self): print self.v.work() return self.v vb1 = ClassB(1) vb2 = ClassB(2) print vb1.value2() print vb1.v print vb1.__class__.v print vb1.v.work() -- http://mail.python.org/mailman/listinfo/python-list