Python face question 2

Source: Internet
Author: User
Tags integer division mul

Question one: What will be the output of the following code? Say your answer and explain.
class Parent(object):    x = 1class Child1(Parent): passclass Child2(Parent): passprint Parent.x, Child1.x, Child2.xChild1.x = 2print Parent.x, Child1.x, Child2.xParent.x = 3print Parent.x, Child1.x, Child2.x

Answer

The output of the above code is:

1 1 11 2 13 2 3

What makes you confused or surprised is that the output of the last line is 3 2 3 not 3 2 1 . Why does changing the value change Parent.x the value Child2.x , but the value does not change at the same time Child1.x ?

The key to this answer is that in Python, class variables are internally processed as dictionaries. If the name of a variable is not found in the dictionary of the current class, the ancestor class (such as the parent class) will be searched until the referenced variable name is found (if the referenced variable name is not found in its own class and not in the ancestor class, an exception is thrown AttributeError ).

Therefore, setting in the parent class causes the x = 1 class variable X to have a value of 1 in reference to the class and any of its subclasses. This is because the output of the first print statement is 1 1 1 .

Then, if any of its subclasses rewrite the value (for example, we execute the statement Child1.x = 2 ), then the value is changed only in the subclass. That's why print the output of the second statement is 1 2 1 .

Finally, if the value is changed in the parent class (for example, we execute the statement Parent.x = 3 ), the change affects the value in any subclass that does not override the value (the subclass that is affected in this example is Child2 ). That's why the third print output is 3 2 3 .

Question two: What will the output of the following code be? Say your answer and explain?
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.)

Answer

The answer actually depends on whether you're using Python 2 or Python 3.

In Python 3, the expected output is:

5/2 = 2.55.0/2 = 2.55//2 = 25.0//2.0 = 2.0

In Python 2, however, the output of the above code would be:

5/2 = 25.0/2 = 2.55//2 = 25.0//2.0 = 2.0

By default, if two operands are integers, Python 2 automatically performs an integer calculation. As a result, the value is 5/2 2 , however, 5./2 a value of ' 2.5 '.

Note that, however, you can reload this behavior in Python 2 (for example, to achieve the same result you want in Python 3) by adding the following import:

from __future__ import division

It is also important to note that the "Double dash" (//) operator will always perform an integer division, regardless of the type of the operand, which is why the 5.0//2.0 value is 2.0 .

Note: In Python 3, the / operator is a floating-point division, and // it is divisible (that is, the quotient has no remainder, such as 10//3 results are 3, the remainder is truncated, and (-7) // 3 the result is -3 .) This algorithm is not the same as many other programming languages, and it is important to note that their division of operations will take a value in the direction of 0. In Python 2, it / is divisible, which is the same as the operator in Python 3. //

Question three: What will the following code output?
list = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]print list[10:]

Answer

The above code will be output [] and will not result in one IndexError .

As expected, attempting to access a member that exceeds the list index value will cause IndexError (for example, access to the above list list[10] ). Nonetheless, attempts to access a list of slices with an out-of-list membership as the starting index will not result IndexError , and will simply return an empty list.

A nasty little problem is that it causes bugs and the problem is difficult to track because it does not raise errors at run time.

Question four: What will the output of the following code be? Say your answer and explain?
def multipliers():    return [lambda x : i * x for i in range(4)]print [m(2) for m in multipliers()]

How you will modify multipliers the definition to produce the desired result

Answer

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

The reason for this is that the late binding of the Python closure results in the late binding, which means that the variables in the closure are looked up when the internal function is called. So the result is that when any multipliers() returned function is called, at that time, i the value is looked up in the scope around which it was called , and by that time, no matter which returned function is called, the for loop is complete, and i the last value is 3 , therefore, The value of each returned function multiplies is 3. So a value equal to 2 is passed above the code, and they will return a value of 6 (for example: 3 x 2).

(By the way, as pointed out in The Hitchhiker's Guide to Python, there is a common misconception, lambda something about expressions.) A lambda function created by an expression is not special, and the presentation is the same as using a normal def created function. )

Here are two ways to solve this problem.

The most common solution is to create a closure that binds its parameters immediately by using the default parameters. For example:

def multipliers():    return [lambda x, i=i : i * x for i in range(4)]

Another option is that you can use the functools.partial function:

from functools import partialfrom operator import muldef multipliers(): return [partial(mul, i) for i in range(4)]
Question five: What will the output of the following code be? Say your answer and explain?
def extendList(val, list=[]):    list.append(val)    return listlist1 = extendList(10)list2 = extendList(123,[])list3 = extendList(‘a‘)print "list1 = %s" % list1print "list2 = %s" % list2print "list3 = %s" % list3

How you will modify extendList the definition to produce the desired result

The output of the above code is:

list1 = [10, ‘a‘]list2 = [123]list3 = [10, ‘a‘]

Many people mistakenly think that list1 should be equal to [10] and list3 should be equal [‘a‘] . The argument is assumed to be list extendList set to its default value each time it is called [] .

However, what actually happens is that the new default list is created only once when the function is defined. It then extendList uses the same list when it is not called by the specified list parameter. This is why when a function is defined, the expression is evaluated with the default argument, not when it is called.

So, list1 and list3 is the same list of operations. 是操作的它创建的独立的列表(通过传递它自己的空列表作为the value of the "List2 list" parameter).

extendList the definition of a function can be modified as follows , but when no new list parameters are specified, a new list is always started, which is more likely to be expected behavior.

def extendList(val, list=None):    if list is None: list = [] list.append(val) return list

With this improved implementation, the output will be:

Select AllCopyput it in your notes .
list1 = [10]list2 = [123]list3 = [‘a‘]

Python face question 2

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.