Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class function not returning the correct value

Tags:

python

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 Answers

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.

like image 188
Óscar López Avatar answered May 04 '26 13:05

Óscar López