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()
-
at the end y=0 cause range(1) returns [0] and x is myclassPradyumna– Pradyumna2012年12月31日 03:49:21 +00:00Commented Dec 31, 2012 at 3:49
2 Answers 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 = {}
7 Comments
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.int is immutable. If OP were using a list or dict it would matter.myclass.aDict['foo'] = 'bar' would be shared among all the instances.int is immutable, though.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.