For the sake of learning, I'm trying to chain decorators that are defined by classes. I read this question about decorators, which has a lot of good information about chaining them with functions. They also link to the documentation, but I'm trying to figure out simpler examples.
Basically, I'm trying to mimic similar behaviour using classes. Here is my first decorator definition, which works perfectly.
class square_result(object):
def __init__(self, f):
pass
def __call__(self, x, y):
return (x+y)**2
@square_result
def add_two_numbers(x, y):
return x + y
print(add_two_numbers(2,5)) #Outputs 49, as expected
Then, I add another decorator to create this code snippet:
class square_result(object):
def __init__(self, f):
pass
def __call__(self, x, y):
return (x+y)**2
class append_abc(object):
def __init__(self, f):
pass
def __call__(self, *args):
return str(*args) + "abc"
@append_abc
@square_result
def add_two_numbers(x, y):
return x + y
print(add_two_numbers(2,5))
#Ideally, this should print "49abc" but prints "(2,5)abc" instead
what is the proper way of doing this? I guess what I want to do is create a decorator in the form of a class that takes the output of the function it decorates (in this case square_result
) and appends "abc"
to it.
I know that when I add a decorator to my code, the add_two_numbers()
function is compiled and that function object is passed to the square_result
class, which does something to create a function-like object which is substituted for the original add_two_numbers()
. However, I'm not sure how to chain this.