Decorators: Python nisse functions.

Posted on

As we are entering the yule it might be time to give an example of the Python programming language equivalent of a yule-nisse: a decorator. A nisse might playfully tease others. Below the “nisse” decorator teases the “add” function and change its behavior:

class nisse(object):    def __init__(self, f):        pass    def __call__(self, x, y):        print 'h??h??'        return x+y+1def add(x,y):    return x+yadd(2,2)@nissedef add(x,y):    return x+yadd(2,2)

When “add(2,2)” is called the first time the result will be 4. The next time with the “nisse” the result will be 5.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s