裝飾器@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ù)。