gath gath - 6 days ago 6
Python Question

How to decorate a method inside a class?

I am attempting to decorate a method inside a class but python is throwing an error. My class looks like this:

from pageutils import formatHeader

myPage(object):
def __init__(self):
self.PageName = ''

def createPage(self):
pageHeader = self.createHeader()

@formatHeader #<----- decorator
def createHeader(self):
return "Page Header ",self.PageName

if __name__=="__main__":
page = myPage()
page.PageName = 'My Page'
page.createPage()

#------- pageutils.py --------------------

def formatHeader(fn):
def wrapped():
return '<div class="page_header">'+fn()+'</div>'
return wrapped


Python throws the following error


self.createHeader()
TypeError: wrapped() takes no arguments (1 given)


Where am I goofing?

Answer

Python automatically passes the class instance as reference. (The self argument which is seen in all class methods).

You could do:

def formatHeader(fn):
    def wrapped(self=None):
        return '<div class="page_header">'+fn(self)+'</div>'
    return wrapped