I have this class:
class test(object):
def __init__(self, s):
self.s = s
def getS(self):
return self.s
I need to generate 5 instances of this class and only 1 instance will have a variable s with a value equal to true.
tests = [test(True) if i==sys.argv[1] else test(False) for i in range(5)]
Then I tried to print the values.
for i in tests:
print i.getS()
Output is:
False
False
False
False
False
Shouldn't one of the value equals to True?
Try this, it's a bit simpler. Also, use xrange if using Python 2.x, or range if using Python 3.x.
tests = [test(i == int(sys.argv[1])) for i in xrange(5)]
Your code is essentially correct - you just forgot to convert to int the command-line argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With