Python topics-----Python seven classic questions __python

Source: Internet
Author: User
1 What the following code outputs.
list = [' A ', ' B ', ' C ', ' d ', ' e ']
print list[10:]

The above code output [] and does not cause a indexerror error

Like you think, when you take a list element, if the index value exceeds the number of elements (for example, in the list above, list[10]) will cause a indexerror error. However, when you take a slice of a list, if the starting index exceeds the number of elements, it will not cause a indexerror error and return only an empty list .

This feature will cause some bugs that are very difficult to track, because there are no errors at run time. 2 What is the output of the following code in Python2. Explain your answers.

def div1 (x,y):
    print "%s/%s =%s"% (x, y, x/y)

def div2 (x,y):
    print "%s//%s =%s"% (x, y, x//y)

Div1 (5,2 )
Div1 (5.,2)
div2 (5,2)
div2 (5.,2.)

In addition, the output of the code above in Python3 is different (assuming that the print statements in the Code are translated into the syntax structure in the Python3).

In Python2 , the output of the code is:

5/2 = 2
5.0/2 = 2.5
5//2 = 2
5.0//2.0 = 2.0

By default, if two operands are integers, Python2 performs an integer operation by default. So the 5/2 result is 2, and the 5./2 result is 2.5.

Note that you can overwrite this behavior in Python2 with the following import statement

From __future__ Import Division 

Also note that the double slash (//) operator will continue to divide evenly , ignoring the type of operand. That's why 5.0//2.0, even in Python2, turns out to be 2.0.

However, when Python3 two operands are integers, no integer operation is performed. In Python3, the output is as follows:

single slashes are divisible by default in Python2 but can be type promoted, Pyhton3 are all in floating-point operation.

5/2 = 2.5
5.0/2 = 2.5
5//2 = 2
5.0//2.0 = 2.0
3 What the output of the following code is. Please explain your answer.
Def extendlist (Val, list=[]):
    List.append (val) return
    list

List1 = Extendlist (a)
List2 = Extendlist (  123,[])
list3 = extendlist (' a ')

print ' List1 =%s '% list1
print ' list2 =%s '% list2
print ' list3 =%s '% List3

How to modify the definition of function extendlist to produce the behavior we want.

The output is:

List1 = [Ten, ' a ']
list2 = [123]
list3 = [Ten, ' a ']

Many people mistakenly predict that list1 equals [10],list3 equals [' a '], that the list parameter of the Extendlist function is set to the default value every time the function is invoked []

However, the real situation is that the default list is created only once when the function is defined. When the Extendlist function is called without specifying a list parameter, the same list is used. This is because the default parameters are computed at the time the function is defined, not when the function is called.


Question: Since the default parameters of Python are computed at definition time, the next call will call the unified list, and the last one should be 24 ...

So, both List1 and List3 are manipulating the same default list, and List2 is manipulating a separate list that it creates (passing its own empty list as a parameter)

The definition of extendlist can be defined in such a way as to achieve our desired effect:

Def extendlist (Val, list=none):
    If list is None:
        list = []
    list.append (val) return
    list

Call the modified function, the output is:

List1 = [ten]
list2 = [123]
list3 = [' A ']
4 What the output of the following code is. Please explain your answer.
Class Parent (object):
    x = 1

class Child1 (parent):
    Pass

class Child2 (parent):
    Pass

Print Parent.x, child1.x, child2.x
child1.x = 2
print parent.x, child1.x, child2.x
parent.x = 3
print Parent.x , child1.x, child2.x

The output is:

1 1 1
1 2 1 3 2 3

What makes many people puzzled and surprised is that the last line of output is not 3 2 1 but 3 2 3. Why modifying the Parent.x value will affect the child2.x, but at the same time does not change the child1.x value.

The key to this problem is that in Python, variables in a class are treated internally as dictionaries. If a variable name is not found in the dictionary of the current class, the system will continue to look for the ancestor of this class (for example, its parent class) until it is found (if a variable name is not in this class or ancestor of this class, a attributeerror error will be raised)

Therefore, the variable x is assigned a value of 1 in the parent class, so the x variable can be referenced by the current class and all subclasses of that class. That's why the first print statement output is 1 1 1.

Next, if its subclass overwrites this value (for example, when we execute child1.x = 2), then the value of the variable is changed only in this subclass. That's why the second print statement outputs 1 2 1

Finally, if the parent class changes the value of the variable (for example, we execute parent.x = 3), all subclasses that do not overwrite the value of the parameter (in this case, Child2) are affected, which is why the output of the third print statement is 3 2 3 5 What the output of the following code is. Please explain your answer.

def multipliers (): return
    [Lambda x:i * x to I in range (4)]

print [M (2) to M in multipliers ()]

How to modify the definition of multipliers to achieve the desired effect.

The output of the above code is [6, 6, 6, 6] (not [0, 2, 4, 6]).

The reason is that python closures are deferred bindings (late binding). This indicates that the variable used in the closure will not be looked up until the inner function is called. As a result, when the function returned by multipliers () is invoked, the value of the I parameter is then looked up in the calling environment. So, regardless of which function the call returns, the For loop ends at this point, I equals its final value of 3. So all returned functions are multiplied by the 3 passed over, because the code above passes 2 as arguments, so they all return 6 (that is, 3 * 2).

(Incidentally, as presented in the book The Hitchhiker's Guide to Python, there is a widespread misconception that this problem is related to lambda expressions, and this is not true.) There is nothing special about functions that are produced by LABDA expressions, and the behavior of functions defined by a normal def is the same as that of a function produced by a lambda expression.

Here are some ways to get around this problem.

Method one is to use the Python Builder (generator) as follows

def multipliers ():
     
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.