Here is a strange behaviour I observed with list
objects in Python
classes.
class Test:
val = []
def __init__(self):
self.val.append(42)
a = Test()
b = Test()
print b.val
The output of above program is [42,42]
rather than the expected [42]
.
class Test:
val = 0
def __init__(self):
self.val+=5
a = Test()
b = Test()
print b.val
In this case the output is 5
as expected.
Following the rule above program showed, this program should have given output 10
. Or vice-versa, the above output should have been only [42]
.
If multiple objects of the same type are instantiated, how are the list
type objects accessible in different objects? This completely defies my OOP
concepts.