python - 将装饰器应用于类中的每个方法?

标签 python decorator

我将装饰器 @login_testuser 应用于方法 test_1():

class TestCase(object):
    @login_testuser
    def test_1(self):
        print "test_1()"

有没有一种方法可以将 @login_testuser 应用于以 "test_" 为前缀的类的每个 方法?

换句话说,装饰器将应用于下面的test_1()test_2() 方法,但不适用于setUp()

class TestCase(object):
    def setUp(self):
        pass

    def test_1(self):
        print "test_1()"

    def test_2(self):
        print "test_2()"

最佳答案

在 Python 2.6 中,一个 class decorator绝对是要走的路。例如,对于这类任务,这是一个非常通用的任务:

import inspect

def decallmethods(decorator, prefix='test_'):
    def dectheclass(cls):
        for name, m in inspect.getmembers(cls, inspect.isfunction):
            if name.startswith(prefix):
                setattr(cls, name, decorator(m))
        return cls
    return dectheclass


@decallmethods(login_testuser)
class TestCase(object):
    def setUp(self):
        pass

    def test_1(self):
        print("test_1()")

    def test_2(self):
        print("test_2()")

会得到你想要的。在 Python 2.5 或更差的版本中,@decallmethods 语法不适用于类修饰,但如果使用其他完全相同的代码,您可以在 之后用以下语句替换它class TestCase 语句结束:

TestCase = decallmethods(login_testuser)(TestCase)

关于python - 将装饰器应用于类中的每个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2237624/

相关文章:

python - SQL 查询(带有 Desc 顺序和限制)不适用于 python (OpenERP)

python - 如何将多维的 pandas 系列转换为 pandas 数据框

python - 如何在调用 dos2unix 以验证 checkin 文件的 SVN 中实现预提交 Hook 脚本

typescript - 如何确保装饰器的参数 "target"扩展 typescript 中的接口(interface)?

javascript - 使用装饰器将属性分配给非原型(prototype)

python - 如何在 python 中覆盖 XML 属性值而不读取整个文件

python - numpy: "array_like"对象的正式定义?

typescript 装饰二传手功能

python - 将单个装饰器应用于多个函数

ejb - CDI:@Decorator @Stateless