Python pass-by-object-reference [TBC]

A function receives a reference to (and will access) the same object in memory as used by the caller.

However, it does not receive the box that the caller is storing this object in; as in pass-by-value,

the function provides its own box and creates a new variable for itself.

  Box Object
Pass-By-Reference Same box Same Object
Pass-By-Value Different box Different value
Pass-By-Object Different box Same object

dis.dis() prints the byte-code instruction.

list += [1,2]  : INPLACE_ADD

list = list + [1,2]   : BINARY_ADD

Python gives types a way to handle += specially, by creating an __iadd__ method as well as an __add__.

The intention is that mutable types, like list, will mutate themselves in __iadd__ (and then return self, unless you're doing something very tricky)

扫描二维码关注公众号,回复: 8474560 查看本文章

Referenced by: 

1. https://stackoverflow.com/questions/15376509/when-is-i-x-different-from-i-i-x-in-python

2.  https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/

猜你喜欢

转载自www.cnblogs.com/noralee/p/12173462.html
TBC
今日推荐