Monday, September 26, 2011

[Level 2] Python Decorator Sample.

Another sample for Python decorator.
#!/usr/bin/env python
class ServiceFee:
  def __init__(self, f):
    self.f = f
    pass
  def __call__(self, *args, **kargs):
    return self.f(*args, **kargs)*1.1

class TaxFee:
  def __init__(self, f):
    self.f = f
    pass
  def __call__(self, *args, **kargs):
    return self.f(*args, **kargs)*1.05

@ServiceFee
@TaxFee
def beef(pricePerKG, KG):
  return pricePerKG*KG

print 'Beef $10/KG, and buy 5KG=%s' % beef(10, 5)
print 'Beef $20/KG, and buy 10KG=%s' % beef(20, 10)

$ ./t.py
Beef $10/KG, and buy 5KG=57.75
Beef $20/KG, and buy 10KG=231.0
Wish this helps. regards, Stanley Huang