class Test(unittest.TestCase): @classmethod def setUpClass(cls): cls.a = 1 def test_01(self): Test.a = self.a + 1 print(Test.a) print(self.a) def test_02(self): self.a = Test().a + 2 print(self.a) def test_03(self): print(self.a) if __name__ == '__main__': unittest.main()
打印:
2
2
4
2
还可以这样(setUpClass如果想要动态的改变某个值一定要使用python的可变的对象比如list,dict):
#coding=utf-8
import
unittest
from
selenium
import
webdriver
class
Mydemo(unittest.TestCase):
@classmethod
def
setUpClass(
cls
):
cls
.a
=
[
0
]
def
test1(
self
):
print
"before update the a in test1 is:{}"
.
format
(
self
.a[
0
])
self
.a[
0
]
=
self
.a[
0
]
+
1
print
"after update the a in test1 is:{}"
.
format
(
self
.a[
0
])
def
test2(
self
):
print
"the value in test2 is:{}"
.
format
(
self
.a[
0
])
@classmethod
def
tearDownClass(
cls
):
print
"I am tearDownClass"
if
__name__
=
=
'__main__'
:
unittest.main()
打印:
before update the a
in
test1
is
:
1
..
after update the a
in
test1
is
:
2
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
the value
in
test2
is
:
1
I am tearDownClass
Ran
2
tests
in
0.001s
如果是int,str,touple