2012-09-26 16 views
5

我曾經在一個基類下面的裝飾:只導入一個類的靜態方法

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,因爲在原始代碼中它們有很長的名字,我必須在很多地方使用它。有任何想法嗎?

編輯: 我決定CHECK_TIME在BaseTests文件中的一個獨立的功能,並簡單地導入

from path.base_posting import BaseTests, check_time 

回答

9

簡而言之

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靜態方法,因爲它看起來像您的使用案例更多地將其用作獨立功能而不是靜態方法。

+1

不錯,謝謝。我正在尋找直接導入方法的解決方案,但您的建議也可以。 – Alex