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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With