3

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?

1
  • 4
    sys.argv is a list of strings, neither of its elements will ever be an integer. (Unless you manually modify it of course.) Try if i == int(sys.argv[1]). Commented Sep 2, 2013 at 22:54

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.