相关疑难解决方法(0)

如何在不为每种方法反复输入的情况下装饰类的所有函数?

让我说我的类有很多方法,我想在每一个方法上应用我的装饰,后来当我添加新方法时,我想要应用相同的装饰器,但我不想在方法声明之上写@mydecorator所有时间?

如果我调查的__call__是正确的方法吗?

重要提示:以下示例似乎解决了与原始问题不同的问题.

编辑:我想以这种方式展示,这是我的问题的类似解决方案,对于任何人后来发现这个问题,使用评论中提到的mixin.

class WrapinMixin(object):
    def __call__(self, hey, you, *args):
        print 'entering', hey, you, repr(args)
        try:
            ret = getattr(self, hey)(you, *args)
            return ret
        except:
            ret = str(e)
            raise
        finally:
            print 'leaving', hey, repr(ret)
Run Code Online (Sandbox Code Playgroud)

然后你可以在另一个

class Wrapmymethodsaround(WrapinMixin): 
    def __call__:
         return super(Wrapmymethodsaround, self).__call__(hey, you, *args)
Run Code Online (Sandbox Code Playgroud)

python decorator wrapper

52
推荐指数
5
解决办法
3万
查看次数

编写一个将装饰器应用于所有方法的类装饰器

我正在尝试编写一个类装饰器,它将装饰器应用于所有类的方法:

import inspect


def decorate_func(func):
    def wrapper(*args, **kwargs):
        print "before"
        ret = func(*args, **kwargs)
        print "after"
        return ret
    for attr in "__module__", "__name__", "__doc__":
        setattr(wrapper, attr, getattr(func, attr))
    return wrapper


def decorate_class(cls):
    for name, meth in inspect.getmembers(cls, inspect.ismethod):
        setattr(cls, name, decorate_func(meth))
    return cls


@decorate_class
class MyClass(object):

    def __init__(self):
        self.a = 10
        print "__init__"

    def foo(self):
        print self.a

    @staticmethod
    def baz():
        print "baz"

    @classmethod
    def bar(cls):
        print "bar"


obj = MyClass()
obj.foo()
obj.baz()
MyClass.baz()
obj.bar()
MyClass.bar()
Run Code Online (Sandbox Code Playgroud)

它几乎可以工作,但@classmethodS需要特殊处理:

$ python …
Run Code Online (Sandbox Code Playgroud)

python decorator

11
推荐指数
1
解决办法
2526
查看次数

标签 统计

decorator ×2

python ×2

wrapper ×1