将装饰器应用于类中的每个方法? [英] Applying a decorator to every method in a class?

查看:44
本文介绍了将装饰器应用于类中的每个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have decorator @login_testuser applied to method test_1():

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

有什么方法可以将 @login_testuser 应用于该类的每个方法的前缀为 test _

Is there a way I can apply @login_testuser on every method of the class prefixed with "test_"?

装饰器将应用于以下 test_1() test_2()方法,但不适用于 setUp ()

In other words, the decorator would apply to test_1(), test_2() methods below, but not on 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中,类修饰器绝对是必经之路。例如,这是用于此类任务的一个非常通用的示例:

In Python 2.6, a class decorator is definitely the way to go. E.g., here's a pretty general one for these kind of tasks:

import inspect

def decallmethods(decorator, prefix='test_'):
  def dectheclass(cls):
    for name, m in inspect.getmembers(cls, inspect.ismethod):
      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 语法不适用于类修饰,但如果使用完全相同的代码,则可以使用以下语句代替类TestCase 语句的结尾之后:

will get you what you desire. In Python 2.5 or worse, the @decallmethods syntax doesn't work for class decoration, but with otherwise exactly the same code you can replace it with the following statement right after the end of the class TestCase statement:

TestCase = decallmethods(login_testuser)(TestCase)

这篇关于将装饰器应用于类中的每个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆