Skip to content Skip to sidebar Skip to footer

Decorate Class-method With Class-decorator

I'm trying to decorate class method using class-decorator. For example class MyDecorator(object): def __init__(self,param1): self.param1 = param1 # do some acti

Solution 1:

classA:
    @MyDecorator("Blablabla")deffunc1(self, arg1, arg2, arg3):
        print (arg1,arg2,arg3)

You need to add the self argument to your function.

Solution 2:

If you prefer to write your func1 method without a first self argument, you need to drop this argument in the decorator:

def__call__(self, func):
    defwrapped(obj, *args, **kwargs):
         # obj is just ignoredprint"in wrapper:"
         func(*args, **kwargs)

This is quite the same as using @staticmethod: when calling a.func1, a is passed as first argument, but this argument is removed by the decorator.

Post a Comment for "Decorate Class-method With Class-decorator"