On Thu, 06 Oct 2005 11:05:10 +0200, Laszlo Zsolt Nagy <[EMAIL PROTECTED]> wrote:
>Hughes, Chad O wrote: > >> Is there any way to create a class method? I can create a class >> variable like this: >> >Hmm, seeing this post, I have decided to implement a 'classproperty' >descriptor. >But I could not. This is what I imagined: > >class A(object): > _x = 0 > @classmethod > def get_x(cls): > print "Getting x..." > return cls._x > @classmethod > def set_x(cls,value): > print "Setting x..." > cls._x = value > x = classproperty(get_x,set_x) > >Usage example: > > >>>print A.x >Getting x >0 > >>>A.x = 8 >Setting x > >>>print A.x >Getting x >8 > >I was trying for a while, but I could not implement a 'classproperty' >function. Is it possible at all? >Thanks, > > Les > Using Peter's advice (not tested beyond what you see): >>> class A(object): ... _x = 0 ... class __metaclass__(type): ... def get_x(cls): ... print "Getting x..." ... return cls._x ... def set_x(cls,value): ... print "Setting x..." ... cls._x = value ... x = property(get_x, set_x) ... >>> A.x Getting x... 0 >>> A.x = 8 Setting x... >>> A.x Getting x... 8 >>> vars(A).items() [('__module__', '__main__'), ('__metaclass__', <class '__main__.__metaclass__'>), ('_x', 8), ('_ _dict__', <attribute '__dict__' of 'A' objects>), ('__weakref__', <attribute '__weakref__' of 'A ' objects>), ('__doc__', None)] >>> A._x 8 >>> vars(A).keys() ['__module__', '__metaclass__', '_x', '__dict__', '__weakref__', '__doc__'] Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list