Recently, when looking at the << fluent python>> about the variable reference section, there are some of their own views, once again recorded.
Problem:
#From flunet Python example 8-8classBus:def __init__(Self, passengers=[]): Self.passengers=passengersdefpick (self, name): Self.passengers,append (name)defRemove (self, name): Self.passengers.remove (name)>> Bus1 = Bus ()#instantiation of>> bus2 = Bus ()#instantiation of>> Bus1.append ('Bob')>>bus2.passengers#Bus2 's passengers also has a value['Bob']
Why does passengers change in BUS1 cause passengers to change in BUS2?
This shows that the two bus instances share a self.passengers, which is clearly two instances?
Looking up, self.passengers refers to the value of passengers, which is the formal parameter (variable) in __init__. This parameter is common in two instances, and the passengers list is used in the instantiation process.
Think again, every time the instantiation process will not create a new passengers it? That's where the problem lies. The answer is passengers. This parameter is not created during instantiation, but is generated when the method is defined. That's because the process is earlier than the instantiation process, Different instances to share the passengers variable.
Define a function again:
def foo (x=[]): print ID (x)>> f1 = foo ()139916453629536> > f2 = foo ()139916453629536
Two times the ID is the same, and the memory space for parameter x is created when the function is defined
Look at the default parameter variables and IDs of the Foo function
>> foo.func_defaults ([],)>> ID (foo.func_defaults[0])139916453629536
You can see that the result of the ID is the same, and also verify that the memory space of the parameter variable was created before the call (defined) .
Looking back, in addition to the argument variable references, there are a few ideas:
(1) method and function parameters are referenced in a consistent way, which creates the memory space at the time of definition
(2) Functions are also examples of function classes
Python variable reference