Python those hard to prevent pit

Preface
the text of text and image from the network, only to learn, exchange, not for any commercial purposes, belongs to original author, if any questions, please contact us for treatment.

Author:  Rocky042 9

In the process of learning Python, I was obsessed with its simplicity and elegance, but it is so naughty, provide a lot of comfort features, it had also quietly dug a pit with a lot of confusing and unpredictable. ...

People can not step twice into the same river, after numerous stepped into the same pit, I think I need to sort out a self-police, two for the reminder to everyone, and I hope you do not make the same mistakes .

0x00 wandered external variables

First, let's look at one such example:


e = 429

try:
   raise Exception()
except Exception as e:
   pass

print(e)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

PS: except Exception as e can catch all exceptions except in addition to associated with the program exits (sys.exit ()).

PS: If you lack the latest python combat tutorial, you can go to small series of Python skirt technology: a Second Five long a second-rate thinking (homonym digital) converter can be found under the

Before continuing to look down, you can start to think about what the results of the above examples may appear that you can also try to look at their own input in the compiler. Thinking over please continue to read.

The results appear as follows:


Traceback (most recent call last):
 File "test.py", line 8, in <module>
   print(e)
NameError: name 'e' is not defined
  • 1
  • 2
  • 3
  • 4

Even being given, so that in the end is why? 

In fact, this is because as a dispensing error in Python3 in time, except at the end of this anomaly will be removed (if such a situation does not arise in Python2 in). It's like the example above into the following way:


e = 429

try:
   raise Exception()
except Exception as e:
   try:
       pass
   finally:
       del e

print(e)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Through the above deformation of the code, we can clearly understand what happened root of all this is: because e has been deleted. It also tells us in disguise, if you want to quote in the back except e, it must first be assigned to other variables. 

It would appear that the variable e is performed except clause is deleted, but why would e except clause to enforce it? Just because a hair long, like e and e back as?


The answer is no, in fact, this is because there is no independent scope clause in Python, so all the contents of the above examples are in the same scope, the variable e because it performed except clause is deleted.



0x01 is also a plus, but not necessarily equivalent

We are represented in "plus" concept of time, usually we will use in two ways: a = a + b or a + = b. In many people's concept of the two it is actually a kind, without distinction, for example, before I was thought so, until one day someone took over the pit below let me step on ... 

First, let's look at the first example:


>>> a = [1,2,3]
>>> b = a
>>> a = a + [4,5,6]
  • 1
  • 2
  • 3

A very simple example, you know at this time how much of a and b, respectively, is not it? Please think about yourself and then continue to look down:


>>> a
[1, 2, 3, 4, 5, 6]
>>> b
[1, 2, 3]
  • 1
  • 2
  • 3
  • 4

Estimated that many people will answer, the expression a = a + [4,5,6], in fact, the right of the equal sign is the formation of a new list, and let a reference to this new list, and b = a reference before of a, b therefore remains unchanged. 

Understand the above example, we are going to look at an example of a little bit of difference:


>>> a = [1,2,3]
>>> b = a
>>> a += [4,5,6]
  • 1
  • 2
  • 3

Examples of the above examples and articles from the beginning of the distinction becomes + + =, as we think about the inertia of thinking, sure maybe that example is a writing two different things only, but in fact is it really? Let us look at this case, a, b: 
>>> a
[1, 2, 3, 4, 5, 6]
>>> b
[1, 2, 3, 4, 5, 6]
  • 1
  • 2
  • 3
  • 4

Huh? The same impression is a "plus", where it seems really a bit different eh.

Through the above we can see that a = a + b and a + = b is not always the same performance, at least on the list is so performance. Here a + = [4,5,6] are actually used extend function, so a and b are still pointing to the same list has been modified.


Now here comes the + and + =, more simply add this: when using the concept of "added" to the connection string, + = + is actually faster than the speed.


Let's look at the actual presentation with three + connection string:


>>> import timeit
>>> timeit.timeit("a = a + b + c", setup="a='a'*10000;b='b'*10000;c='c'*10000",number=100)
0.07921688999340404
>>> timeit.timeit("a += b + c", setup="a='a'*10000;b='b'*10000;c='c'*10000",number=100)
0.002059974998701364
  • 1
  • 2
  • 3
  • 4
  • 5

The above two results can easily see that, in the processing speed, + = much faster than the speed of the process +. The reason for this phenomenon is that + = append operation is performed, then additional operations would be less and the destruction of the new action than a +, such as the A + b + c a = will not be destroyed. 

0x02 unusual parentheses

Many learned other programming language students, it is easy to ignore parentheses "()" an important manifestation in Python, that is a small parenthesis can not represent the "tuple" change data types.


>>> type(())
<class 'tuple'>
>>> tur = (1, 2)
>>> type(tur)
<class 'tuple'>
  • 1
  • 2
  • 3
  • 4
  • 5

But if only one element within the parentheses, then, for example like this, it is the element type in parentheses: 
>>> tur = (1)
>>> type(tur)
<class 'int'>
  • 1
  • 2
  • 3

Gee a day ... 

So if you want to represent an element tuple Zezheng it? To look like this:


>>> tur = (1, )
>>> type(tur)
<class 'tuple'>
  • 1
  • 2
  • 3

Add a comma "," Just ok it ... 

Delete 0x03 list is not so simple

If we have a list, I want to delete the list of elements: 
>>> lst = [1, 2, 3, 4, 5]
>>> for i in lst:
... lst.remove(i)
  • 1
  • 2
  • 3

In just learning Python beginning, it is easy to think of the practice of many students, however, we look at the results after the program finishes running: 
>>> lst
[2, 4]
  • 1
  • 2

See the results, I ...

Here Insert Picture Description


This is for the wisdom of it? Because the for loop, if we remove the index = 0 (or 1) value, the original index value = 1 and beyond fill the seats forward, so the current index value index = = before the value of 1 of 2 .


Deletion of the list we often use, so we should be playing twelfth of the spirit of it.



0x04 is not, regardless of family

is not to be a group in Python, use the time to rely on together, after just two separate things, the result will be different ...


>>> [1, 2, 3] is not None
True
>>> [1, 2, 3] is (not None)
False
 
  • 1
  • 2
  • 3
  • 4

It is, is not a separate binary operator, when the variable it on both sides point to the same object, the result is False, otherwise the result is True, hope to attract everyone's attention.

Guess you like

Origin www.cnblogs.com/bianchenjiaoshou/p/11919685.html