In a nutshell. You create two instances and you assign the same list to both of them which you instantiate when you run your code. >>> id(spam_1.list) 4530230984 # <- Here >>> id(spam_2.list) 4530230984 # <- Here >>> id(spam_1) 4530231632 # Nice unique instance >>> id(spam_2) 4530231200 # Nice unique instance as well
Try >>> class Foo: ... def __init__(self, list=None): ... self.list = list ... >>> spam_1 = Foo() >>> spam_2 = Foo([]) <- Cheating. >>> spam_1 <__main__.Foo instance at 0x10e05d9e0> >>> spam_2 <__main__.Foo instance at 0x10e05d950> >>> spam_2.list.append(42) >>> print(spam_1.list) None >>> print(spam_2.list) [42] >>> id(spam_1.list) 4527705752 >>> id(spam_2.list) 4530231488 Or something along those lines :) On 21 April 2017 at 16:03, Guyzmo via Python-Dev <python-dev@python.org> wrote: > On Fri, Apr 21, 2017 at 11:47:24AM +0200, Justus Schwabedal wrote: >> At least I think it's a bug. Maybe it's a feature.. > > it's indeed a feature. > >> I possibly found a bug in class __init__ and would like to fix it > > technically, it's a method. More precisely, it's the constructor method. > >> So I'm looking for a mentor to help me. >> >> class Foo: >> def __init__(self, bar=[]): >> self.list = bar >> >> spam_1 = Foo() >> spam_2 = Foo() >> >> spam_1.list.append(42) >> print(spam_2.list)` > > the argument `bar` of your method is instanciated at the time you're > declaring the method. It's happening once for the the lifetime of the > execution of your code. > > By allocating the `bar` reference into the `self.list` member, you're > assigning the same *instance* of that list into the `self.list` member. > > So everytime you create a new Foo instance, you're actually assigning > the same `[]` instance into `self.list` which is why, when you mutate > the list, it's happening in all the instances of Foo as well. > > I hope it makes sense to you ! > > -- > Guyzmo > _______________________________________________ > Python-Dev mailing list > Python-Dev@python.org > https://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: > https://mail.python.org/mailman/options/python-dev/mmavrofides%40gmail.com -- "Only those who will risk going too far can possibly find out how far one can go. "T.S. Eliot http://0x109.tuxfamily.org _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com