简体   繁体   English

嵌套函数作为Python中的属性

[英]Nested function as attribute in Python

Not sure if this is a dupe or not. 不知道这是不是骗子。 Here it goes. 来了

I need to write some Python code that looks like: 我需要编写一些类似以下的Python代码:

class TestClass:
    def test_case(self):
     def get_categories(self):
      return [“abc”,”bcd”]
     # do the test here

and then have a test engine class that scans all these test classes, loads all the test_case functions and for each invokes get_categories to find out if the test belongs t the group of interest for the specific run. 然后有一个测试引擎类,该类扫描所有这些测试类,加载所有的test_case函数,并为每个调用get_categories的对象找出该测试是否属于特定运行的关注组。

The problem is that get_categories is not seen as an attribute of test_case, and even if I manually assign it 问题是get_categories不会被视为test_case的属性,即使我手动分配它也是如此

class TestClass:
    def test_case(self):
     def get_categories(self):
      return [“abc”,”bcd”]
     # do the test here
     test_case.get_categories = get_categories

this is only going to happen when test_case first runs, too late for me. 这只会在test_case第一次运行时发生,对我来说太晚了。

The reason why this function can't go on the class (or at least why I want it to be also available at the per-function level) is that a TestClass can have multiple test cases. 该函数不能在类上运行的原因(或者至少为什么我希望每个函数级别都可以使用它)的原因是TestClass可以具有多个测试用例。 Since this is an already existing testing infrastructure, and the categories mechanism works (other than the categories-on-function scenario, which is of lesser importance), a rewrite is not in the plans. 由于这是一个已经存在的测试基础结构,并且类别机制起作用(除了“功能类别类别”方案(重要性较低)以外),因此计划中没有重写。

Language tricks dearly appreciated. 语言技巧很受赞赏。

Nested functions don't become attributes any more than any other assignment. 嵌套函数不会像其他任何赋值一样成为属性。

I suspect your test infrastructure is doing some severely weird things if this isn't supported (and uses old-style classes!), but you could just do this: 我怀疑您的测试基础结构是否在做一些严重的怪异的事情(如果不支持,并且使用老式的类!),但是您可以这样做:

class TestClass:
    def test_case(self):
        # ...

    def _get_categories(self):
        return [...]
    test_case.get_categories = _get_categories
    del _get_categories

Class bodies are executable code like any other block. 类主体是可执行代码,就像其他任何块一样。

What you need is nested classes. 您需要的是嵌套类。 Functions aren't made to do what you are trying to do, so you have to move up a notch. 函数并不是按照您想做的去做的,因此您必须向上移动一个档次。 Function attributes are mainly used as markup, whereas classes can have anything you want. 函数属性主要用作标记,而类可以具有所需的任何内容。

class TestClass(object):
    class TestCase(object):
         @classmethod
         def get_categories(cls):
             return ['abc', 'efg']

Note that I used @classmethod so that you could use it without instantiating TestCase() ; 请注意,我使用了@classmethod以便您可以在不实例化TestCase()情况下使用它; modify if you want to do test_case = TestCase() . 修改是否要执行test_case = TestCase()

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

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