gath gath - 1 year ago 92
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

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'

#------- --------------------

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

Python throws the following error

TypeError: wrapped() takes no arguments (1 given)

Where am I goofing?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download