Custom Search

Saturday, May 14, 2011

python decorator class examples

class FormatMe:
def __init__(self, fun):
self.fun = fun

def __call__(self, name):
return self.fun(name)+2

@FormatMe
def add_test(num):
return num

print "----------", add_test(6)

#######################

class FormatMe:
def __init__(self, const):
self.const = const

def __call__(self, func):
def _wrapper(name):
return func(name)+self.const
return _wrapper

@FormatMe(100)
def add_test(num):
return num

print "----------", add_test(6)

######################

class FormatMe:
def __init__(self, const):
self.const = const

def __call__(self, func):
def _wrapper(name):
return func(name)+self.const
return _wrapper

@FormatMe(const=200)
def add_test(num):
return num

print "----------", add_test(6)

Output
======

---------- 8
---------- 106
---------- 206

No comments:

Post a Comment