Emulate @classmethod using decorator and descriptor

WaterWalk toolmaster at 163.com
Tue Dec 12 06:46:43 EST 2006


Hello, I was recently learning python decorator and descriptor and
emulated a @classmethod decorator:
class EmuClassMethod(object):
    def __init__(self, f=None):
        self.f = f
    def __get__(self, obj, klass=None):
        if klass is None:
           klass = type(obj)
        def  wrapped(*args):
           return self.f(klass, *args)
        return wrapped

class Test(object):
    @EmuClassMethod
    def t(cls):
        print "I'm %s" % cls.__name__

It worked, and seems that a function decorator works as follows:
# decf is a decorator
@decf
def func():
    print 'func'

will be "converted" to:

def func():
    print 'func'
func = decf(func)

Is this really the case? Or correct me if i'm wrong. Thanks in advance.




More information about the Python-list mailing list