相关疑难解决方法(0)

将装饰器附加到类中的所有函数

我真的不需要这样做,但只是想知道,有没有办法将装饰器绑定到类中的所有函数,而不是明确地为每个函数声明它.

我认为它然后变成了一种方面,而不是装饰者,它确实感觉有点奇怪,但是想到时间或认证这样的东西它会非常整洁.

python oop class decorator class-method

47
推荐指数
4
解决办法
1万
查看次数

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

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

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
查看次数

如何在传递参数的所有类函数调用之前/之后运行方法?

在诸如Python: Do Something for any method of a class? 等问题中,有一些有趣的方法可以在类中的每个方法之前运行方法。

然而,该解决方案不允许我们传递参数。

对于类中的所有函数,有一个关于捕获“函数调用之前/之后”事件的装饰器解决方案,但我不想返回并装饰我的所有类。

有没有一种方法可以运行依赖于每次调用对象方法时传递的参数的前/后操作?

例子:

class Stuff(object):
    def do_stuff(self, stuff):
        print(stuff)

a = Stuff()
a.do_stuff('foobar')
"Pre operation for foobar"
"foobar"
"Post operation for foobar"
Run Code Online (Sandbox Code Playgroud)

python metaprogramming python-2.7 python-3.x

6
推荐指数
1
解决办法
5099
查看次数