简体   繁体   English

用class-decorator装饰class-method

[英]Decorate class-method with class-decorator

I'm trying to decorate class method using class-decorator. 我正在尝试使用class-decorator装饰类方法。 For example 例如

class MyDecorator(object):
    def __init__(self,param1):
        self.param1 = param1
        # do some action with param1

    def __call__(self,func):
        def wrapped(*args,**kwargs):
             print "in wrapper:"
             func(*args,**kwargs)

        return wrapped

and my some class: 和我的一些班级:

class A:
    @MyDecorator("Blablabla")
    def func1(arg1,arg2,arg3):
         print (arg1,arg2,arg3)

but when I do the next action: 但是当我执行下一个动作时:

a = A()
a.func(1,2,3)

I get the following error: 我收到以下错误:

TypeError: func1() takes exactly 3 arguments (4 given)
class A:
    @MyDecorator("Blablabla")
    def func1(self, arg1, arg2, arg3):
        print (arg1,arg2,arg3)

You need to add the self argument to your function. 您需要将self参数添加到函数中。

If you prefer to write your func1 method without a first self argument, you need to drop this argument in the decorator: 如果您想编写不带第一个self参数的func1方法,则需要在装饰器中删除此参数:

def __call__(self, func):
    def wrapped(obj, *args, **kwargs):
         # obj is just ignored
         print "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. 这与使用@staticmethod :调用a.func1a作为第一个参数传递,但此参数已由装饰器删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM