【问题标题】:Import only a class static method只导入一个类静态方法
【发布时间】:2012-09-26 14:03:31
【问题描述】:

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

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

【问题讨论】:

    标签: python inheritance import


    【解决方案1】:

    简单地说

    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 设为静态方法,因为您的用例似乎更多地将其用作独立函数而不是静态方法。

    【讨论】:

    • 很好,谢谢。我一直在寻找直接导入该方法的解决方案,但您的建议也有效。
    猜你喜欢
    • 2012-12-13
    • 2015-04-22
    • 1970-01-01
    • 2011-10-19
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 2019-08-31
    相关资源
    最近更新 更多