仅导入类静态方法



我在基类中有以下装饰器:

class BaseTests(TestCase):
    @staticmethod
    def check_time(self, fn):
        @wraps(fn)
        def test_wrapper(*args,**kwargs):
            # do checks ...
        return test_wrapper

以及从 BaseTests 继承的以下类:

from path.base_posting import BaseTests
from path.base_posting.BaseTests import check_time  # THIS LINE DOES NOT WORK!
class SpecificTest(BaseTests):
    @check_time # use the decorator
    def test_post(self):
        # do testing ...
我想如上所述在

SpecificTest 中使用装饰器,而不必使用 BaseTests.check_time,因为在原始代码中它们的名称很长,我必须在很多地方使用它。有什么想法吗?

编辑:我决定在 BaseTests 文件中check_time一个独立的函数,然后简单地导入

from path.base_posting import BaseTests, check_time

简单地说

check_time = BaseTests.check_time

在第二个模块中:


from module_paths.base_posting import BaseTests
check_time = BaseTests.check_time
class SpecificTest(BaseTests):
    @check_time # use the decorator
    def test_post(self):
        # do testing ...

您可能还需要重新考虑将check_time作为静态方法,因为您的用例似乎更多地将其用作独立函数,而不是静态方法。

最新更新