Jamesla
Jamesla

Reputation: 1408

Simple strange basic python behaviour

Does anybody know why this below code prints 0 and 1 rather than 5 and 2, in csharp similar code would print 5 and 2 and I am just trying to work out the logic here.

class Myclass:
    a = 0
    b = 1 

def foo():
    for x in range(1):
        for y in range(1):
            myclass = Myclass()
            if y == 1:
                myclass.a = 5
            if y == 1:
                myclass.b = 2
            ClassList.append(Myclass)

    for x in ClassList:
        print x.a   
        print x.b

ClassList = []
foo()   

Upvotes: 1

Views: 71

Answers (2)

jdi
jdi

Reputation: 92569

Because y is never 1:

>>> range(1)
[0]

What you want is range(2)

And just incase you are not aware... currently you are using a and b as class attributes as opposed to instance attributes. For your specific case of doing value assignments, you won't see a problem, but if you were to have defined say, dictionaries or lists, and were changing keys/indices of those objects, it would be the same object shared across all of the instances.

class Myclass(object):
    a = []
    b = {}

obj1 = Myclass()
obj2 = Myclass()
obj1.a.append('foo')
obj1.b['biz'] = 'baz'
print obj2.a
# ['foo']
print obj2.b
# {'biz': 'baz'}

... vs instance attributes

class Myclass(object):
    def __init__(self):
        self.a = []
        self.b = {}

Upvotes: 2

Dolda2000
Dolda2000

Reputation: 25855

The reason is that range(1) returns [0], not [0, 1], so your y == 1 test never evaluates to true.

Also, you're appending Myclass rather than myclass -- that is, the actual class, rather than the instance you created -- to the list, so you're always printing the unmodified a and b from the class.

Upvotes: 1

Related Questions