Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

python - Import only a class static method

I have the following decorator in a base class:

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

And the following class inheriting from 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 ...

I would like to use the decorator in SpecificTest as above, without having to use BaseTests.check_time, because in the original code they have long names, and I have to use it in many places. Any ideas?

EDIT: I decided to make check_time an independent function in BaseTests file, and simply import

from path.base_posting import BaseTests, check_time
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply put

check_time = BaseTests.check_time

in your second module:


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

You may also want to reconsider making check_time a staticmethod, since it appears your use case employs it more as a stand-alone function than as a staticmethod.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...