17 things you should know about Python programmers

Source: Internet
Author: User
Tags define local

1. Do not use a mutable object as the default function value.
Copy codeThe Code is as follows: In [1]: def append_to_list (value, def_list = []):
...: Def_list.append (value)
...: Return def_list
...:

In [2]: my_list = append_to_list (1)

In [3]: my_list
Out [3]: [1]

In [4]: my_other_list = append_to_list (2)

In [5]: my_other_list
Out [5]: [1, 2] #. Actually, we only wanted to generate [2], but brought in the first running effect page.

In [6]: import time

In [7]: def report_arg (my_default = time. time ()):
...: Print (my_default)
...:

In [8]: report_arg () # first execution
1399562371.32

In [9]: time. sleep (2) #2 seconds

In [10]: report_arg ()
1399562371.32 # Time has not changed
What are the two examples? Dictionary, set, list, and other objects are not suitable as default values of functions. because this default value is generated when the function is created, the "cache" of this object is used for each call ". I shared this problem with python advanced programming in the previous period. This is a problem encountered in actual development. Check the code you have learned. It may be that the problem has not been exposed.

You can change it as follows:
Copy codeThe Code is as follows:
Def append_to_list (element, to = None ):
If to is None:
To = []
To. append (element)
Return

II. The generator does not retain the results after iteration.
Copy codeThe Code is as follows: In [12]: gen = (I for I in range (5 ))

In [13]: 2 in gen
Out [13]: True

In [14]: 3 in gen
Out [14]: True

In [15]: 1 in gen
Out [15]: False #1 Why not in gen? Because 1-> 2 is called, 1 is no longer in the iterator and is generated on demand.

In [20]: gen = (I for I in range (5 ))

In [21]: a_list = list (gen) # It can be converted to a list. Of course, a_tuple = tuple (gen) can also be converted to a list.

In [22]: 2 in a_list
Out [22]: True

In [23]: 3 in a_list
Out [23]: True

In [24]: 1 in a_list # Even if the loop is passed, the value is still
Out [24]: True

3. lambda saves local variables in the closure.
Copy codeThe Code is as follows:
In [29]: my_list = [lambda: I for I in range (5)]

In [30]: for l in my_list:
...: Print (l ())
....:
4
4
4
4
4
This problem is still explained in the above-mentioned python advanced programming for specific reasons. in fact, when I assign a value to my_list, the lambda expression executes the I loop until I = 4, And I retains

However, a generator can be used.
Copy codeThe Code is as follows:
In [31]: my_gen = (lambda: n for n in range (5 ))

In [32]: for l in my_gen:
...: Print (l ())
....:
0
1
2
3
4
You can also stick to the following:
Copy codeThe Code is as follows:
In [33]: my_list = [lambda x = I: x for I in range (5)] # I assigned the default value to each lambda expression

In [34]: for l in my_list:
...: Print (l ())
....:
0
1
2
3
4
A little hard to understand, right? Look at another magic in python:
Copy codeThe Code is as follows:
In [35]: def groupby (items, size ):
...: Return zip (* [iter (items)] * size)
....:

In [36]: groupby (range (9), 3)
Out [36]: [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
A grouping function does not seem easy to understand, right? Let's analyze it here
Copy codeThe Code is as follows:
In [39]: [iter (items)] * 3
Out [39]:
[<Listiterator at 0x10e155fd0>,
<Listiterator at 0x10e155fd0>,
<Listiterator at 0x10e155fd0>] # As you can see, it turns items into iteratable and repeats three times (the same object), but don't forget, every time. next (), so it plays the role of grouping
In [40]: [lambda x = I: x for I in range (5)]
Out [40]:
[<Function _ main _. <lambda>,
<Function _ main _. <lambda>,
<Function _ main _. <lambda>,
<Function _ main _. <lambda>,
<Function _ main _. <lambda>] # understand?


4. Modify the list items in a loop
Copy codeThe Code is as follows: In [44]: a = [1, 2, 3, 4, 5]

In [45]: for I in:
...: If not I % 2:
...: A. remove (I)
....:

In [46]:
Out [46]: [1, 3, 5] # No problem

In [50]: B = [2, 4, 5, 6]

In [51]: for I in B:
...: If not I % 2:
...: B. remove (I)
....:

In [52]: B
Out [52]: [4, 5] # the result I wanted should be to remove the even list.
Think about why-the removal of the list affects its index.
Copy codeThe Code is as follows:
In [53]: B = [2, 4, 5, 6]

In [54]: for index, item in enumerate (B ):
...: Print (index, item)
...: If not item % 2:
...: B. remove (item)
....:
(0, 2) # No problem here 2 deleted
(1, 5) # Because 2 is deleted, the current list is [4, 5, 6], so index list [1] goes directly to 5, ignoring 4
(2, 6)

5. The value of IndexError-list exceeds the number of indexes.
Copy codeThe Code is as follows:
In [55]: my_list = [1, 2, 3, 4, 5]

In [56]: my_list [5] # This element does not exist at all
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<Ipython-input-56-037d00de8360> in <module> ()
----> 1 my_list [5]

IndexError: list index out of range # throwing an exception

In [57]: my_list [5:] # but you can do this. You must note that if you use it properly, it's trick. If you use it wrong, it's a pitfall.
Out [57]: []

Vi. Reuse global variables
Copy codeThe Code is as follows:
In [58]: def my_func ():
...: Print (var) # I can call an undefined variable first.
....:

In [59]: var = 'global' # post-assignment

In [60]: my_func () # You only need to define the variable when calling the function.
Global

In [61]: def my_func ():
...: Var = 'locally changed'
....:

In [62]: var = 'global'

In [63]: my_func ()

In [64]: print (var)

Global # local variables do not affect global variables

In [65]: def my_func ():
...: Print (var) # although you set this variable globally, local variables have the same name. python thinks you forgot to define local variables.
...: Var = 'locally changed'
....:

In [66]: var = 'global'

In [67]: my_func ()
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<Ipython-input-67-d82eda95de40> in <module> ()
----> 1 my_func ()

<Ipython-input-65-0ad11d690936> in my_func ()
1 def my_func ():
----> 2 print (var)
3 var = 'locally changed'
4

UnboundLocalError: local variable 'var' referenced before assignment

In [68]: def my_func ():
...: Global var # at this time, we need to add global
...: Print (var) # This way you can use it normally.
...: Var = 'locally changed'
....:

In [69]: var = 'global'

In [70]:

In [70]: my_func ()
Global

In [71]: print (var)
Locally changed # The global variable is changed when global is used.

7. Copy a variable object
Copy codeThe Code is as follows: In [72]: my_list1 = [[1, 2, 3] * 2

In [73]: my_list1
Out [73]: [1, 2, 3], [1, 2, 3]

In [74]: my_list1 [1] [0] = 'A' # I only modify one item In the sublist.

In [75]: my_list1
Out [75]: [['A', 2, 3], ['A', 2, 3] #

In [76]: my_list2 = [[1, 2, 3] for I in range (2)] # using this loop to generate different objects will not affect

In [77]: my_list2 [1] [0] = 'A'

In [78]: my_list2
Out [78]: [[1, 2, 3], ['A', 2, 3]


VIII. python multi-inheritance (C3)
Copy codeThe Code is as follows:
In [1]: class A (object ):
...: Def foo (self ):
...: Print ("class ")
...:

In [2]: class B (object ):
...: Def foo (self ):
...: Print ("class B ")
...:

In [3]: class C (A, B ):
...: Pass
...:

In [4]: C (). foo ()
Class A # The example is very understandable. C inherits A and B, from left to right, and finds that A has the foo method and returns

It seems to be very simple, with an order from the bottom up, from the back to the back, find and return. Let's look at the example again:
Copy codeThe Code is as follows:
In [5]: class A (object ):
...: Def foo (self ):
...: Print ("class ")
...:

In [6]: class B ():
...: Pass
...:

In [7]: class C ():
...: Def foo (self ):
...: Print ("class C ")
...:

In [8]: class D (B, C ):
...: Pass
...:

In [9]: D (). foo ()
Class C #? In principle, the order is D-> B-> A. Why did I find C?
This involves MRO (Method Resolution Order ):
Copy codeThe Code is as follows:
In [10]: D. _ mro __
Out [10]: (_ main _. D, _ main _. B, _ main _. C, _ main _. A, object)
A simple understanding is that the new category is breadth-first. D-> B. But C inherits from A. C first, and then.

9. List + and + =, append and extend

Copy codeThe Code is as follows: In [17]: print ('Id: ', ID (a_list ))
('Id: ", 4481323592)

In [18]: a_list + = [1]

In [19]: print ('Id (+ =): ', ID (a_list ))
('Id (+ =): ', 4481323592) # Use + = or operate on the original list

In [20]: a_list = a_list + [2]

In [21]: print ('Id (list = list +...): ', ID (a_list ))
('Id (list = list +...): ', 4481293056) # simple + actually changed the original list
In [28]: a_list = []

In [29]: id (a_list)
Out [29]: 4481326976

In [30]: a_list.append (1)

In [31]: id (a_list)
Out [31]: 4481326976 # append is added to the original list

In [32]: a_list.extend ([2])

In [33]: id (a_list)
Out [33]: 4481326976 # extend is also added to the original list

10. datetime also has a Boolean value.
This is a pitfall
Copy codeThe Code is as follows:
In [34]: import datetime

In [35]: print ('"datetime. time (, 0)" (Midnight)->', bool (datetime. time (, 0 )))
('"Datetime. time (0, 0)" (Midnight)->', False)

In [36]: print ('"datetime. time (, 0)" (1 am)->', bool (datetime. time (, 0 )))
('"Datetime. time (, 0)" (1 am)->', True)


11. Differences between '=' and is
In my understanding, "is" is used to determine the identities of two objects, and = is used to determine the values of two objects.
Copy codeThe Code is as follows:
In [37]: a = 1

In [38]: B = 1

In [39]: print ('A is B ', bool (a is B ))
('A is B ', True)

In [40]: c = 999.

In [41]: d = 999.

In [42]: print ('C is D', bool (c is d ))
('C is D', False) # The reason is that python memory management caches objects ranging from-5 to 256.

In [43]: print ('2017 is 257-1 ', 256 is 256-1)
('1970 is 257-1 ', True)

In [44]: print ('2017 is 258-1 ', 257 is 257-1)
('1970 is 258-1 ', False)

In [45]: print ('-5 is-6 + 1',-5 is-6 + 1)
('-5 is-6 + 1', True)

In [46]: print ('-7 is-6-1',-7 is-6-1)
('-7 is-6-1', False)
In [47]: a = 'Hello world! '

In [48]: B = 'Hello world! '

In [49]: print ('A is B, ', a is B)
('A is B, ', False) # obviously they are not cached. This is an object with two field strings.

In [50]: print ('a = B, ', a = B)
('A = B, ', True) # But their values are the same
# But, there is a special case
In [51]: a = float ('nan ')

In [52]: print ('A is a, ', a is)
('A is a, ', True)

In [53]: print ('a = a, ', a =)
('A = a, ', False) # highlight my eyes ~


12. Shallow copy and deep copy
In actual development, we can modify the object of a list, but we may not want to change the original list. the shortest copies only the parent object, and the deep copy also copies the internal sub-objects of the object.
Copy codeThe Code is as follows:
In [65]: list1 = [1, 2]

In [66]: list2 = list1 # Is a reference. If you operate list2, the result of list1 will change.

In [67]: list3 = list1 [:]

In [69]: import copy

In [70]: list4 = copy. copy (list1) # He and list3 are both shortest copies.

In [71]: id (list1), id (list2), id (list3), id (list4)
Out [71]: (4480620232,448 0620133, 4479667880,449 4894720)

In [72]: list2 [0] = 3

In [73]: print ('list1: ', list1)
('List1: ', [3, 2])

In [74]: list3 [0] = 4

In [75]: list4 [1] = 4

In [76]: print ('list1: ', list1)
('List1: ', [3, 2]) # list3 and list4 operations have no effect on list1

# Let's take a look at the differences between deep copy and shallow copy.

In [88]: from copy import copy, deepcopy

In [89]: list1 = [1], [2]

In [90]: list2 = copy (list1) # or shortest copy

In [91]: list3 = deepcopy (list1) # Deep copy

In [92]: id (list1), id (list2), id (list3)
Out [92]: (4494896592,449 5349160, 4494896088)

In [93]: list2 [0] [0] = 3

In [94]: print ('list1: ', list1)
('List1: ', [[3], [2]) # see it. If you operate on its sub-objects, the source is still affected as it is referenced.

In [95]: list3 [0] [0] = 5

In [96]: print ('list1: ', list1)
('List1: ', [[3], [2]) # Deep copy will not be affected

13. bool is actually a subclass of int.
Copy codeThe Code is as follows:
In [97]: isinstance (True, int)
Out [97]: True

In [98]: True + True
Out [98]: 2

In [99]: 3 * True + True
Out [99]: 4

In [100]: 3 * True-False
Out [100]: 3

In [104]: True <10
Out [104]: 1024

Are the tuples immutable?
Copy codeThe Code is as follows: In [111]: tup = ([],)

In [1, 112]: tup [0] + = [1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<Ipython-input-112-d4f292cf35de> in <module> ()
----> 1 tup [0] + = [1]

TypeError: 'tuple' object does not support item assignment

In [113]: tup
Out [113]: ([1],) # When I rely on it, it turns my eyes bright again. Can I modify it even if an exception is thrown?

In [114]: tup = ([],)

In [1, 115]: tup [0]. extend ([1])

In [116]: tup [0]
Out [116]: [1] # Well, I have a bit of understanding. Although I cannot directly operate on tuples, I cannot block the variable sub-objects (list) IN THE tuples)

Here Is a good explanation of Python's + = Is Weird, Part II:
Copy codeThe Code is as follows:
In [117]: my_tup = (1 ,)

In [118]: my_tup + = (4 ,)

In [119]: my_tup = my_tup + (5 ,)

In [1, 120]: my_tup
Out [120]: (1, 4, 5 )#? Why can't I operate tuples?

In [121]: my_tup = (1 ,)

In [122]: print (id (my_tup ))
4481317904

In [123]: my_tup + = (4 ,)

In [124]: print (id (my_tup ))
4480606864 # The operation is not the original tuples, so you can

In [125]: my_tup = my_tup + (5 ,)

In [126]: print (id (my_tup ))
4474234912

No private methods/variables in python? But there can be "pseudo"
Copy codeThe Code is as follows:
In [127]: class my_class (object ^ E ):
...: Def public_method (self ):
...: Print ('Hello public world! ')
......: Def _ private_method (self): # The private name starts with a double underline.
...: Print ('Hello private world! ')
...: Def call_private_method_in_class (self ):
...: Self. _ private_method ()

In [1, 132]: my_instance = my_class ()

In [133]: my_instance.public_method ()
Hello public world! # Common method

In [134]: my_instance. _ my_class _ private_method ()
Hello private world! # You can add "_ + class name + private method name" to a private method"

In [135]: my_instance.call_private_method_in_class ()
Hello private world! # It can also be accessed through the public interface provided by the class

In [136]: my_instance. _ my_class _ private_variable
Out [136]: 1

17. Exception Handling plus else
Copy codeThe Code is as follows:
In [150]: try:
...: Print ('third element: ', a_list [2])
...: Cannot t IndexError:
...: Print ('raised indexerror ')
...: Else:
...: Print ('no error in try-Block') # The expression in else is executed only when there is no exception in try.
.....:
Raised IndexError # failed to complete throwing an exception
In [153]: I = 0

In [154]: while I <2:
...: Print (I)
...: I + = 1
...: Else:
...: Print ('in else ')
.....:
0
1
In else # while is also supported ~
In [155]: I = 0

In [156]: while I <2:
...: Print (I)
...: I + = 1
...: Break
...: Else:
...: Print ('completed while-loop ')
.....:
0 # If it is break, the else will not be executed after it is fully executed.
In [158]: for I in range (2 ):
...: Print (I)
...: Else:
...: Print ('completed for-loop ')
.....:
0
1
Completed for-loop

In [159]: for I in range (2 ):
...: Print (I)
...: Break
...: Else:
...: Print ('completed for-loop ')
.....:
0 # it's also because of break.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.