”Python Easy to “ It seems to have become the consensus of many developers , You bet , Its expression has been very close to natural language . Don't look like C++ Think about pointers like that 、 Memory , It doesn't have to be like Java So in-depth understanding JVM.
gradual , Developers began to think for sure ” The code we wrote is completely correct “.
however , Ignoring Python The details of the process , Will find , There will be strange mistakes . When looking back for positioning , There is no problem with the positioning , Search on the Internet can not find the corresponding solution , Looking back at the code , I think the code With no chink in one's armour . Little imagine , Many mistakes have been made in the development process .
this paper , Just summarize 5 individual Python Mistakes that beginners often encounter . To be honest with you , There are some mistakes I stepped on at the beginning , And can't escape for a long time , I hope to summarize these problems , To avoid people stepping into the pit again !
In some cases , You need to make a copy of the dictionary . This copy is used to save the original data , Then the original dictionary will participate in other operations , Or pass it as a parameter to some functions .
for example ,
>>> dict_a = {"name": "John", "address":"221B Baker street"}
>>> dict_b = dict_a Use the assignment method to put dict_a Assign a value to dict_b after , this 2 The values of variables are the same .
You may take it dict_b To participate in other operations , for example , to update / Add key value pair .
But the truth is not what you think , If you update or edit dict_b,dict_a It's going to change , You can learn more about Python Mutable objects versus immutable objects .
Let's take a look at the effect :
>>> dict_b["age"] = 26
>>> dict_b
{'address': '221B Baker street', 'name': 'John', 'age': 26}
>>> dict_a
{'address': '221B Baker street', 'name': 'John', 'age': 26} You'll find that , to dict_b Added a age:26 Key value pair ,dict_a Also updated , such , There is no point in leaving a copy .
In response to this question , It can be used Python The shallow copy in copy、 Deep copy deepcopy To solve , So let's see ,
>>> dict_c = dict_b.copy()
>>> dict_c["location"] = "somewhere"
>>> dict_c
{'address': '221B Baker street', 'name': 'John', 'age': 26, 'location': 'somewhere'}
>>> dict_b
{'address': '221B Baker street', 'name': 'John', 'age': 26}First , Let's take an example ,
>>> dict_a = dict()
>>> dict_a
{}
>>> dict_a[1] = "apple"
>>> dict_a[True] = "mango"
>>> dict_a[2] = "melon"
>>> dict_a
{1: 'mango', 2: 'melon'}Did you notice what happened ?
After outputting the dictionary , Key value found True period !
This is because , stay Python in ,True amount to 1、False amount to 0, therefore , stay dict_a[True] = "mango" In this line of code , It sets the original key value to 1 Replaced with .
You can verify True amount to 1 That's what I'm saying :
>>> isinstance(True, int) True >>> True == 1 True
Again , First look at an example of a list :
>>> list_a = [1,2,3,4,5] >>> list_a = list_a.append(6) >>> list_a # Don't output anything
Take another example of a dictionary :
>>> dict_a = {"a" : "b"}
>>> dict_a = dict_a.update({"c" : "d"})
>>> dict_a
# Don't output anything Find out , Print list_a and dict_a There is no content output !
This is because , stay Python Middle list 、 Some methods in the dictionary , Such as sorting 、 to update 、 additional 、 Add, etc , Do not create unnecessary copies , To improve performance , therefore , There is no need to reassign to variables .
Take another look at the correct method :
>>> list_a = [1,2,3,4,5] >>> list_a.append(6) >>> list_a.sort() >>> list_a [1, 2, 3, 4, 5, 6]
In some cases ,Python Try reusing existing immutable objects . String persistence is such a case .
Let's see an example comparison ,
>>> a = "gmail" >>> b = "gmail" >>> a is b True
Then make a change ,
>>> a = "@gmail" >>> b = "@gmail" >>> a is b False
Isn't that amazing ? We only added one @ Symbol , The results are very different !
In the first implementation method , Try creating two different string objects . But when checking whether the two objects are the same , It returns True.
This is because python Not creating another object b, It's going to be b Points to the first value gmail, In other words, it is resident .
however , If the string is divided by ASCII character 、 Numbers 、 Characters other than underscores , It will not reside , In this case , It will no longer point to @gmail.
There's a little bit of caution here ,is And == The operation of is different .
== Used to judge value Whether it is equal or not ,is Not only do values need to be equal , You also need to point to the same object .
>>> a = "@gmail" >>> b = "@gmail" >>> a is b False >>> a == b True
Let's take a look at the following example :
>>> def func(a, lst=[]): ... lst.append(a) ... return lst ... >>> print(func(1)) [1] >>> print(func(2)) [1, 2]
What happened here ?
I am here func A default parameter is given in [], And then it was called 2 Time func function .
According to our conventional understanding , this 2 Calls are separate , The first 1 Call output [1], The second time should output [2], Why the 2 At the time of the first call, the number... Is still reserved in the list 1 The value at the time of the call ?
This is because , stay Python in , The default parameter will only be calculated once . The first 1 Secondary call func(1) when , It uses default parameters . however , The first 2 This call will no longer calculate the default parameters , Directly in [1] Add a value on the basis of .
This article introduces these common mistakes , Maybe you haven't met , Therefore, I will feel disapproval . however , Always at some point 、 This is unconsciously used when developing a small module 5 One of the functions covered by the question .
If you take it for granted , Do as we think in our concept , The result is predictable , There will be errors .
therefore , stay Python Development process , Attention should be paid to some details , Study deeply and systematically Python, Avoid in some Python Make some mistakes in basic characteristics .
If you are right about Python Have a deep understanding of , Naturally, these mistakes will be avoided . conversely , It will bring you big trouble , Once there is a mistake, it is difficult to locate .