Object reference, variability, garbage collection,
8.1 Variable not box
This chapter is relatively more than the concept, I've pre-cursory read it again, I think the selection of classic records.
a = [1 ,2, 3]
Follow the instructions in calligraphy, the correct understanding that the variable (variable name) a assigned to the object ([1,2,3])
After all, the object has been created before the assignment.
To understand the assignment statement in Python, you should always first read right. Objects created on the right or acquisition, after which the variable on the left will be bound to the object, which is like an object affixed label.
8.2 identifier, alias and equality
a = 1
b = a
a and b are aliases, because they also bind an object
id is determined whether two variables are equal.
ID must be unique numerical labels, and never become the object lifecycle.
8.3 default do shallow copy
General copy (copy) is shallow copy, shallow copy is to copy the outermost container, elements within the copy is a reference element in the container, the advantage is to save memory.
l = [1, [2, 3, ], 'ok'] l1 = list(l) l2 = l[:] l3 = l.copy()
The above three kinds is shallow copy. To copy the outermost, unless there are elements of immutable elements, copy elements or else there is a reference, or will cause problems.
Do deep copy to any object:
import copy class Bus: def __init__(self, passengers =None): if passengers is None: self.passengers = [] else: self.passengers = list(passengers) def pick(self, name): self.passengers.append(name) def drop(self, name): self.passengers.remove(name) if __name__ == '__main__': bus1 = Bus(['1', '2', '3']) bus2 = copy.copy(bus1) bus3 = copy.deepcopy(bus1) # 用了copy内部的属性引用还是一样的 print(id(bus1.passengers),id(bus2.passengers),id(bus3.passengers)) bus1.drop('2') print(bus1.passengers, bus2.passengers, bus3.passengers, sep='\n')
/usr/local/bin/python3.7 /Users/shijianzhong/study/Fluent_Python/第八章/t8_8.py 4563857312 4563857312 4563740464 ['1', '3'] ['1', '3'] ['1', '2', '3'] Process finished with exit code 0
copy the copied object, copy only the outermost layer, inside the property references address are the same.
Participation 8.4 function as a reference
The only parameter passing shared support parameter passing mode Python.
Shared parameters Parameter form respective transfer function means to obtain a copy of each argument a reference direct said internal parameter argument function alias.
When the parameter is passed in a variable type, the internal parameter change parameters, arguments also occurs outside the conversion.
8.4.1 Do not use the variable type as a parameter default values
# t8_12 class HauntedBus: def __init__(self, passengers=[]): self.passengers = passengers def pick(self, name): self.passengers.append(name) def drop(self, name): self.passengers.remove(name)
from t8_12 import HauntedBus In [78]: bus2 = HauntedBus() In [79]: bus2.pick('sidian') In [80]: bus3 = HauntedBus() In [81]: bus3.passengers Out[81]: ['sidian'] In [82]: bus2.passengers is bus3.passengers Out[82]: True In [84]: bus2.__init__.__defaults__ Out[84]: (['sidian'],) In [85]: bus3.pick('gray') In [86]: bus2.__init__.__defaults__ Out[86]: (['sidian', 'gray'],) In [87]: HauntedBus.__init__.__defaults__ Out[87]: (['sidian', 'gray'],) In [88]: bus2.__init__.__defaults__ Out[88]: (['sidian', 'gray'],) In [89]: import dis In [90]: dis.dis(HauntedBus) Disassembly of __init__: 4 0 LOAD_FAST 1 (passengers) 2 LOAD_FAST 0 (self) 4 STORE_ATTR 0 (passengers) 6 LOAD_CONST 0 (None) 8 RETURN_VALUE Disassembly of drop: 10 0 LOAD_FAST 0 (self) 2 LOAD_ATTR 0 (passengers) 4 LOAD_METHOD 1 (remove) 6 LOAD_FAST 1 (name) 8 CALL_METHOD 1 10 POP_TOP 12 LOAD_CONST 0 (None) 14 RETURN_VALUE Disassembly of pick: 7 0 LOAD_FAST 0 (self) 2 LOAD_ATTR 0 (passengers) 4 LOAD_METHOD 1 (append) 6 LOAD_FAST 1 (name) 8 CALL_METHOD 1 10 POP_TOP 12 LOAD_CONST 0 (None) 14 RETURN_VALUE
Why this is so because the definition of the function of time (usually at load time), the default value becomes the property function object.
So when the function definition, refers to the variable default parameters, also sends the same problem.
8.5 del garbage and recycling
del delete is the name of a variable, but not the object.
Python garbage clear that the main use of technology is a reference, in addition to generational collection, mark cleared.
For some examples cited weak, weak references can help you get the object, but the object will not increase the number of references.
Python 3.7.4 (default, Jul 9 2019, 18:13:23) Type 'copyright', 'credits' or 'license' for more information IPython 7.7.0 -- An enhanced Interactive Python. Type '?' for help. PyDev console: using IPython 7.7.0 Python 3.7.4 (default, Jul 9 2019, 18:13:23) [Clang 10.0.1 (clang-1001.0.46.4)] on darwin import weakref, sys s1 = {1,2,3} s2 = s1 def bye(): print('Gone with the wind...') ender = weakref.finalize(s1 ,bye) sys.getrefcount(s1) Out[7]: 3 del s2 sys.getrefcount(s1) Out[9]: 2 ender.alive Out[10]: True del s1 Gone with the wind... ender.alive Out[12]: False
After I repeatedly debugging, execution in the shell, the object weakref.ref example in the book acquired the object, if implemented (), inside the object labels directly increase a lot. But it can be performed in py file inside.
Py file in the code before the normal execution of:
weakref Import Import SYS of a_set 0 = {,}. 1 FUNC the lambda = X: Print (the repr (X), 'IS Deleting') Wref = weakref.ref (of a_set, FUNC) Print (sys.getrefcount (of a_set)) Print (Wref ()) Print (sys.getrefcount (of a_set)) of a_set = {0, #}. 1 recopied, delete old notes corresponding to variable print (wref ())
/usr/local/bin/python3.7 /Users/shijianzhong/study/Fluent_Python/第八章/t8_17.py 2 {0, 1} 2 <weakref at 0x10d0976b0; dead> is deleting None Process finished with exit code 0
Then the code is written in python console:
/usr/local/bin/python3.7 /Applications/PyCharm.app/Contents/helpers/pydev/pydevconsole.py --mode=client --port=54889 import sys; print('Python %s on %s' % (sys.version, sys.platform)) sys.path.extend(['/Users/shijianzhong/study', '/Users/shijianzhong/study/Fluent_Python/第六章']) Python 3.7.4 (default, Jul 9 2019, 18:13:23) Type 'copyright', 'credits' or 'license' for more information IPython 7.7.0 -- An enhanced Interactive Python. Type '?' for help. PyDev console: using IPython 7.7.0 Python 3.7.4 (default, Jul 9 2019, 18:13:23) [Clang 10.0.1 (clang-1001.0.46.4)] on darwin import weakref import sys a_set = {0, 1} func = lambda x: print(repr(x), 'is deleting') wref = weakref.ref(a_set, func) print(sys.getrefcount(a_set)) 2 wref() Out[3]: {0, 1} sys.getrefcount(a_set) Out[4]: 9
Notes objects suddenly became 9, then there is no back thing.
Provided behind weakref
The In [225]: weakref.WeakKeyDictionary
Out [225]: weakref.WeakKeyDictionary
the In [226]: weakref.WeakValueDictionary
Out [226]: weakref.WeakValueDictionary
the In [227]: weakref.WeakSet
Out [227]: _weakrefset.WeakSet
three module, I used a bit WeakSet modules, or very interesting, add a class attribute in a WeakSet inside, all objects are alive in this WeakSet inside, you can easily view live examples.
Import WeakSet weakref from class My_Demo: instances = WeakSet () DEF the __init __ (Self, name): the self.name name = My_Demo.instances.add (Self) # initialized when the instances into WeakSet () inside my1 = My_Demo ( 'MY1') MY2 = My_Demo ( 'MY2') del MY2 # delete one example MY3 = My_Demo ( 'MY3') Print (My_Demo.instances) Print (my1.instances) # by way of example may of course be invoked class properties.
/usr/local/bin/python3.7 /Users/shijianzhong/study/Fluent_Python/第八章/t8_19_1.py <_weakrefset.WeakSet object at 0x107f1e3d0> <_weakrefset.WeakSet object at 0x107f1e3d0> Process finished with exit code 0
Summary (individuals excerpt two points):
Simple assignment does not create a copy
Of + =, * = augmented assignment done, if the left variable binding is an immutable object, the object is created, if it is a variable object, the place modification.
Originally understanding of the book I put a variable, the variable name, aliases, can be understood as the same thing, in = left.
= Right is the object, is the first with the left = created.
= Left is labeled the objects above, but also that point to objects, or objects such as shortcuts.
We can not delete an object, you can only delete the left = number, and other objects on top of all the notes are ripped up, the object will ascend to heaven.
So later when writing the program, some unused objects can del off to avoid wasting memory.