Wednesday, March 9, 2011

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

The sample of Python decorator (1, by class):
#!/usr/bin/env python
class my_de:
  def __init__(self, f):
    self.f = f
  def __call__(self, *args, **kargs):
    print 'Before you call the method (%s)' % self.f.__name__
    self.f(*args, **kargs)
    print 'After you call the method (%s)' % self.f.__name__

@my_de
def helloworld(who, are, you):
  print 'hello world! %s %s %s' % (who, are, you)

if __name__ == '__main__':
  helloworld('I', 'am', 'Stanley')

Execute it.
$ ./t.py
Before you call the method (helloworld)
hello world! I am stanley
After you call the method (helloworld)


The sample of Python decorator (2, by wrap function):
#!/usr/bin/env python
def my_de(f):
  def new_f(*args, **kargs):
    print 'Before you call the method (%s)' % f.__name__
    f(*args, **kargs)
    print 'After you call the method (%s)' % f.__name__
  return new_f

@my_de
def helloworld(who, are, you):
  print 'hello world! %s %s %s' % (who, are, you)

if __name__ == '__main__':
  helloworld('I', 'am', 'Stanley')

Execute it.
$ ./t.py
Before you call the method (helloworld)
hello world! I am Stanley
After you call the method (helloworld)


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

Wish this helps.
regards,
Stanley Huang