Understand the difference between cumulative assignment to variables and cumulative assignment to objects

Objects (values) and variables

In Python, None, numbers, functions, classes, methods, modules, etc. ** all ** are ** converted ** to ** objects ** (instances of some class). The ** variable ** holds the ** object id **, which is the ** reference value ** to the object **. You can ** assign ** to any object. You can also ** reassign ** objects of a different type. ** Variables ** are stored in the ** Variable Dictionary ** with ** variable name ** as the dictionary key and ** object id ** as the dictionary value. You can check the contents of the ** variable dictionary ** with the vars function, locals function, and globals function. The ** list ** is a ** array ** of ** object id **. You can also assign / reassign objects of different types for each array element.

Variable assignment / reassignment

image.png

>>> id(1)
15812500000
>>> type(1)
<class'int'>
>>> 1 .__class__    #Insert a space before the dot so that it is not interpreted as a decimal point
<class'int'>
>>> 1 .real
1
>>> id(2)
15812500032
>>> a = 1
>>> id(a)
15812500000
>>> a = 2
>>> id(a)
15812500032
>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class'_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
 'a': 2}

Cumulative assignment to variables Part 1: In the case of immutable objects

Assignments such as + = are called cumulative assignments. Cumulative assignment in Python behaves differently depending on whether the object assigned to the variable is an immutable (immutable) object or a mutable (variable) object. For immutable objects such as int type, reassign another object as shown in the figure below.

image.png

>>> a = 2
>>> id(a)
15812500032
>>> a += 1
>>> id(a)
15812500064

List object

image.png

>>> id(1)
15812500000
>>> id(2)
15812500032
>>> id(3)
15812500064
>>> a = [1, 2, 3]
>>> id(a)
123145300973832
>>> type(a)
<class'list'>
>>> a.__class__
<class'list'>
>>> len(a)
3
>>> a.__len__()
3
>>> for ele in a:
...     print(ele, type(ele), id(ele))
...
1 <class'int'> 15812500000
2 <class'int'> 15812500032
3 <class'int'> 15812500064
>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class'_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
 'a': [1, 2, 3],
 'ele': 3}

Cumulative assignment to an object

image.png

>>> a = [1, 2, 3]
>>> id(a[0])
15812500000
>>> a[0] += 1
>>> id(a[0])
15812500032
>>> id(a[1])
15812500032

Note that integer values (int type objects) from -5 to 256 are cached as frequently used values and are ** shared and reused **, so ʻa [0]and ʻa [1]The object ids are the same. Object-oriented Design Patterns (https://en.wikipedia.org/wiki/%E3%83%87%E3%82%B6%E3%82%A4%E3%83%B3%E3%83%91 % E3% 82% BF% E3% 83% BC% E3% 83% B3_ (% E3% 82% BD% E3% 83% 95% E3% 83% 88% E3% 82% A6% E3% 82% A7% E3% 82% A2)) "[flyweight pattern](https://ja.wikipedia.org/wiki/Flyweight_%E3%83%91%E3%82%BF%E3%83%BC%E3%83" % B3) ”is used.

Cumulative assignment to variables # 2: For mutable objects

Since the list is a mutable object, it behaves differently than an int type object. As shown in the figure below, the object is requested to process, and the object itself changes the object contents.

image.png

>>> a = [1, 2, 3]
>>> id(a)
123145300973832
>>> hasattr(a, '__iadd__')
True
>>> hasattr(2, '__iadd__')
False
>>> a += [4]
>>> id(a)
123145300973832
>>> len(a)
4
>>> a.__len__()
4
>>> id(a[3])
15812500096

reference

Cumulative assignment statement: https://docs.python.org/ja/3/reference/simple_stmts.html#augmented-assignment-statements Cumulative assignment method: https://docs.python.org/ja/3/reference/datamodel.html#object.iadd

Recommended Posts

Understand the difference between cumulative assignment to variables and cumulative assignment to objects
How to use argparse and the difference between optparse
I don't really understand the difference between modules, packages and libraries, so I tried to organize them.
[Introduction to Python] What is the difference between a list and a tuple?
What is the difference between `pip` and` conda`?
[python] Difference between variables and self. Variables in class
About the difference between "==" and "is" in python
About the difference between PostgreSQL su and sudo
What is the difference between Unix and Linux?
Understand the TensorFlow namespace and master shared variables
Consideration of the difference between ROC curve and PR curve
The rough difference between Unicode and UTF-8 (and their friends)
Can BERT tell the difference between "candy (candy)" and "candy (rain)"?
Difference between Ruby and Python in terms of variables
What is the difference between usleep, nanosleep and clock_nanosleep?
[Introduction to Infectious Disease Models] What is the difference between the April epidemic and this epidemic? .. .. ‼
What is the difference between a symbolic link and a hard link?
Difference between process and job
Difference between "categorical_crossentropy" and "sparse_categorical_crossentropy"
About Python variables and objects
Difference between regression and classification
I want to absorb the difference between the for statement on the Python + numpy matrix and the Julia for statement
"Deep copy" and "Shallow copy" to understand with the smallest example
I tried to enumerate the differences between java and python
Difference between np.array and np.arange
The difference between foreground and background processes understood by the principle
Difference between MicroPython and CPython
Difference between ps a and ps -a
Difference between return and print-Python
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
Difference in how to write if statement between ruby ​​and python
I investigated the behavior of the difference between hard links and symbolic links
Try to implement and understand the segment tree step by step (python)
Difference between Ruby and Python split
Difference between java and python (memo)
Difference between list () and [] in Python
Difference between SQLAlchemy filter () and filter_by ()
Difference between == and is in python
Memorandum (difference between csv.reader and csv.dictreader)
(Note) Difference between gateway and default gateway
Difference between Numpy randint and Random randint
Difference between sort and sorted (memorial)
Difference between python2 series and python3 series dict.keys ()
[Python] Difference between function and method
Difference between SQLAlchemy flush () and commit ()
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)
I want to separate the processing between test time and production environment
How to get the date and time difference in seconds with python
Look up the names and data of free variables in function objects
[Xg boost] Difference between softmax and softprob
difference between statements (statements) and expressions (expressions) in Python
Record the steps to understand machine learning
[Django ORM] Difference between values () and only ()
Difference between PHP and Python finally and exit
Difference between @classmethod and @staticmethod in Python
Difference between append and + = in Python list
Difference between nonlocal and global in Python
Difference between linear regression, Ridge regression and Lasso regression
[Python] Difference between class method and static method