python 面试必读

总结了10道题的考试侧重点,供参考: 
1.How are arguments passed – by reference of by value? 
考的是语法,基本功,虽说python程序员可以不用关心堆栈指针那些头疼的东东,但传引用和传值的区别还是必需清楚的。个人感觉从python中一切都是对象的角度看,第一题问传值还是传引用其实是考官有意看面试者是不是概念清楚,真正希望考生回答的是哪些对象传递到函数中是只读的或者说不可变的。 

2.Do you know what list and dict comprehensions are? Can you give an example? 
印象中 list and dict comprehensions 语法比一般循环的实现简洁了很多很多,不过说实在的由于之前用多了其他语言,后来转用python的话真不太习惯。 

两个常见的例子: 

>>> print {i : chr(65+i) for i in range(4)} 
{0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'} 

S = [2 * x for x in range(101) if x ** 2 > 3] 

3.What is PEP 8? 
第3题 PEP8是众多pythoner们使用的编码规范,很多公司已经直接使用PEP8了,如果连看还没看过的朋友请马上看下吧:http://www.python.org/dev/peps/pep-0008/ 
面试中如果你还能说说PEP7,以及使用它们的感受,相信考官肯定会给你加分。 

4.Do you use virtual environments? 
是不是有独立配开发环境的能力。 virtual environments 给开发人员进行多版本、多环境下的开发调试带来了极大的便利,很难想象没有Virtualenv,多版本开发有多头大,不是不成,别跟自己过不去不是。 
推荐: 
http://pythoncentral.org/how-to-install-virtualenv-python/ 
https://pypi.python.org/pypi/virtualenv 

5.Can you sum all of the elements in the list, how about to multuply them and get the result? 
>>> data = ['5', '4', '9'] 
>>> sum(int(i) for i in data) 
18 
>>>reduce(lambda x, y: x+int(y), data, 0) 
18 

>>> data = [5, 4, 9] 
>>> sum(data) 
18 
>>> reduce(lambda x, y: x*y, data) 
180 
>>> 

6.Do you know what is the difference between lists and tuples? Can you give me an example for their usage? 
list 和 tuple 的不同首先是的语法,相同点都是类似数组的容器,都可以保存任意类型的对象,不同是tuple中的元素不可变,list中的元素是可以改变的,因此list比tuple多了一些管理其中保存元素的方法,如append, insert, pop, remove, sort, reverse等。 

值得一提的是 Python 2.6 开始有了tuple 的子类 collections.namedtuple 可以通过元素的名字访问tuple了 (因为它具有 attribute 语法) ,当然还可以进过元素索引下标访问。 

常见的例子是: 

import collections 
freturn = collections.namedtuple('freturn', 'fee fie foo fum') 

def f(): 
... 
return freturn(fee, fie, foo, fum) 

#读取返回值: 

r = f() 
print r.fie # 相当于print r[1] , 但是提高了代码的可读性 

7.Do you know the difference between range and xrange? 
使用中最大的区别是在内存上,另外还可以看下*里的解答:http://*.com/questions/94935/what-is-the-difference-between-range-and-xrange 

值得注意的是python3里的range函数相当于python2的xrange。 

8.Tell me a few differences between Python 2.x and 3.x 
希望你对新老产品都有所关注, 2/3的区别参考: 
http://docs.python.org/release/3.0/whatsnew/3.0.html 
http://www.python.org/dev/peps/pep-3000/ 

9.What are decorators and what is their usage? 
@classmethod大家一定都用,关于Decorators的说明(by Bruce Eckel): 
http://www.artima.com/weblogs/viewpost.jsp?thread=240808 

http://www.python.org/dev/peps/pep-0318/ 
Decorators for Functions and Methods 

10.The with statement and its usage. 
典型的pythonic语法