22

基本クラスに次のデコレータがあります。

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 ...

元のコードでは長い名前があり、多くの場所で使用する必要があるため、BaseTests.check_time を使用せずに、上記のように SpecificTest でデコレータを使用したいと思います。何か案は?

編集: baseTests ファイルで check_time を独立した関数にし、単純にインポートすることにしました

from path.base_posting import BaseTests, check_time
4

1 に答える 1

28

簡単に言えば

check_time = BaseTests.check_time

2番目のモジュールで:


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-09-26T14:05:41.643 に答える