How to optimise this code?
Nils Oliver Kröger
NO_Kroeger at gmx.de
Tue Aug 21 13:29:23 EDT 2007
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
David N Montgomery schrieb:
> class testCase:
> def __init__(self, tc):
> if tc == 1:self.testCase1()
> if tc == 2:self.testCase2()
> if tc == 3:self.testCase3()
> if tc == 4:self.testCase4()
> if tc == 5:self.testCase5()
> if tc == 6:self.testCase6()
>
> def testCase1(self):
> print "tc1"
>
> def testCase2(self):
> print "tc2"
>
> def testCase3(self):
> print "tc3"
>
> def testCase4(self):
> print "tc4"
>
> def testCase5(self):
> print "tc5"
>
> def testCase6(self):
> print "tc6"
>
>
> def testCaseX(self):
> print "tcX"
>
> totalNumberOfTestCases = 6
> x = 0
> while x <= totalNumberOfTestCases:
> x += 1
> testCase(x)
>
>
> This template code is working, but I envisage having 100+ test cases and
> am concerned about my useage of if statements. I would be grateful for
> any pointers as to how I can run all tests cases, regardless of how
> many, in a more efficient manner.
>
> Thank you in advance.
Hi,
generally a flexible way to avoid huge blocks of if elsif elsif elsif
... ad infintum is to use pythons built in dictionary like this:
class Test:
def __init__(self):
self.cases = {1:self.test1,
2:self.test2,
3:self.test3
}
self._member = "I'm Test"
def test1(self, param):
print "one"
print param
print self._member
def test2(self, param):
print "two"
print param
print self._member
def test3(self, param):
print "three"
print param
print self._member
if __name__ == "__main__":
t = Test()
for x in range(1, 4):
t.cases[x](x)
hope that helps ...
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iD8DBQFGyyDxzvGJy8WEGTcRAn2XAJ97z8o6Sxpi7euPtPUsm/FrD1bgEgCfeRcs
TKzwnkIdbs3GRI0yXcVUugM=
=HIJc
-----END PGP SIGNATURE-----
More information about the Python-list
mailing list