Lemon Tiger Lemon Tiger - 3 months ago 15
Python Question

Why does this Python 2.6 code return a zero?

The following is some simple Python 2.6 code that I wrote. The code works as expected, except I am curious why a zero (0) is returned in the output?

Thank you very much!

class One(object):
def __init__(self):
self.A = 0

def Two(self, *args):
for x in args:
if x == 1:
print x
return self

def answer(self):
print (self.A)

ABC = One()
ABC.Two(1, 1, 9, 0, 7).answer()


OUTPUT

1
1
0
Process finished with exit code 0

BPL BPL
Answer

Maybe if you write it differently you'll understand what's going on:

class One(object):

    def __init__(self):
        self.A = 0

    def Two(self, *args):
        for x in args:
            if x == 1:
                print x
        return self

    def answer(self):
        print(self.A)

ABC = One()
ABC.Two(1, 1, 9, 0, 7)
print '-' * 80
ABC.answer()

As you can see, the method answeris the one returning zero, not the method Two

Comments