1

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() 
asked Dec 31, 2012 at 3:39
1
  • at the end y=0 cause range(1) returns [0] and x is myclass Commented Dec 31, 2012 at 3:49

2 Answers 2

2

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 = {}
answered Dec 31, 2012 at 3:43
Sign up to request clarification or add additional context in comments.

7 Comments

"This means settings myclass.a = 5 will set it for the entire class, shared." <-- This is not true. Evaluating myclass.a = 5 will always modify the instance's __dict__, regardless of whether the name is defined in the class' __dict__ or not.
I was just about to delete that. int is immutable. If OP were using a list or dict it would matter.
No, it would still not matter.
I understand you mean assignments. I am simply pointing out that the OP is using class attributes in case they were not aware. Doing something like myclass.aDict['foo'] = 'bar' would be shared among all the instances.
Sure enough, that is true. Not because int is immutable, though.
|
1

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.

answered Dec 31, 2012 at 3:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.