classmethod和setUpClass的用法

裝飾器@staticmethod、@classmethod

https://taizilongxu.gitbooks.io/stackoverflow-about-python/content/14/README.html

class A(object): 
    def foo(self,x): 
        print "executing foo(%s,%s)"%(self,x) 
    @classmethod 
    def class_foo(cls,x): 
        print "executing class_foo(%s,%s)"%(cls,x) 
    @staticmethod 
    def static_foo(x): 
        print "executing static_foo(%s)"%x
a=A()
a.class_foo(1)
A.class_foo(1)
a. static_foo(1)
A. static_foo(1)

用classmethod裝飾的是類方法,可以通過類直接調(diào)用,類方法的第一個(gè)參數(shù)不是類的對(duì)象實(shí)例,而是類;而普通的方法則是必須通過類的實(shí)例對(duì)象去調(diào)用,所以第一個(gè)參數(shù)都會(huì)是類的實(shí)例self;
用static method裝飾的方法,不管傳遞給第一個(gè)參數(shù)的是self (對(duì)象實(shí)體)還是cls(類).它們的表現(xiàn)都一樣。靜態(tài)方法,說到底它就是一個(gè)方法

setUpClass

我的代碼中有這樣的用法:

class HelloTests(unittest.TestCase):   
      @classmethod    
      def setUpClass(cls):#setUpClass must be a class method  
          ****
      @classmethod
      def tearDownClass(cls):     
             cls.driver.quit()
      def test_process(self):
           ****

setup、teardown方法在每執(zhí)行一個(gè)TestCase時(shí),都會(huì)重新執(zhí)行一遍,
當(dāng)只想要在整個(gè)文件中進(jìn)行一次setup和teardown操作的時(shí)候,可以用setUpClass、tearDownClass,注意哦:他們只是函數(shù)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容