Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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  class 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?

like image 992
gath Avatar asked Sep 02 '09 12:09

gath


People also ask

How do you make a decorator inside a classroom?

Inside Class A “fun1” Instance Method is calling the decorator function “Decorators” inside Class B “fun2”. Instance Method is calling the decorator function of Class A. To use the decorator of Class A, we must require using Class name in which decorator is present that's why we use “@A. Decorators” here.

What is a class method decorator?

The @classmethod decorator is a built-in function decorator which is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition. A class method receives the class as the implicit first argument, just like an instance method receives the instance.

Can we use decorators on class in Python?

In Python, decorators can be either functions or classes. In both cases, decorating adds functionality to existing functions. When we decorate a function with a class, that function becomes an instance of the class. We can add functionality to the function by defining methods in the decorating class.

What are method decorators in Python?

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.


1 Answers

You are omitting the self parameter which is present in the undecorated function (createHeader in your case).

def formatHeader(fn):     from functools import wraps     @wraps(fn)     def wrapper(self):         return '<div class="page_header">'+fn(self)+'</div>'     return wrapper 

If you are unsure about the signature of the function you want to decorate, you can make it rather general as follows:

def formatHeader(fn):     from functools import wraps     @wraps(fn)     def wrapper(*args, **kw):         return '<div class="page_header">'+fn(*args, **kw)+'</div>'     return wrapper 
like image 132
krawyoti Avatar answered Sep 24 '22 06:09

krawyoti