class - Strange behaviour when inheriting from a list in python -
I was recently negligible with heritage and I am a little confused with the following:
In-Place Method method2
works but does not do first?
Because how in-place operators work.
self = self + [cheese]
creates a new list and put it in the local variable self
, overriding passed one, but This object does not modify itself internally, it adds self = self .__ __ ([cheese])
.
self + = [thing]
, otooh, place. Internally it tries to self = self .__ iadd __ ([thing])
first. iadd
means "Install Ad" only if it does not exist, then is self-self .___ Add __ ([thing])
is called.
The difference is that __ add __ ()
always creates a new object and leaves others untouched __iadd __ ()
, though , Is considered the first attempt to run on the modified object. In this case, it gives returns so that the object's change is not, i. E. refers itself to the same object as before. If this is not possible, then it returns a new one which is then assigned.
Comments
Post a Comment