Monday, September 26, 2011

[Level 2] How to implement decorator in Python (II).

Months ago, I wrote a simple decorator, without decorator parameters, implement in Python.
[Level 2] How to implement decorator in Python (I).
Now, I'll show you how to implement decorator with parameter.

The sample of Python decorator (1, by class):
#!/bin/env python

class Decorator:
    def __init__(self, man, woman):
        self.man = man 
        self.woman = woman
        pass
    def __call__(self, f): 
        def wrapped_f(*args, **kargs):
            print 'hello %s' % self.man
            f(*args, **kargs)
            print 'world %s' % self.woman
        return wrapped_f

@Decorator('stanley', 'christy')
def test(who):
    print 'test(%s)' % who 
   
test('joseph') 
$ ./test.py
hello stanley
test(joseph)
world christy

The sample of Python decorator (2, by wrap function):
#!/bin/env python
def Decorator(man, woman):
    def wrap(f):
        def wrapped_f(*args, **kargs):
            print 'hello %s' % man 
            f(*args, **kargs)
            print 'world %s' % woman
        return wrapped_f
    return wrap

@Decorator('stanley', 'christy')
def test(who):
    print 'test(%s)' % who 

test('joseph')

$ ./test.py
hello stanley
test(joseph)
world christy

Wish this helps.
regards,
Stanley Huang