您的位置:首页 > 编程语言 > Python开发

python 面试题1

2015-10-18 23:22 609 查看

python 面试题 - 知识点整理

分类: python面试2013-03-05 15:52 13754人阅读 评论(1) 收藏 举报
python面试题

目录(?)[+]

1. 在判断object是否是class的instances时,type和isinstance函数的区别?

type(obj) => <type 'instance'>

type(cls) => <type 'classobj'>

由上可知,所有obj type后统一为 instance type; 而cls type后统一为classobj type

isinstance(obj,class),如果object是class的instance,返回True。

2. 通过重写内建函数,实现文件open之前检查文件格式?

[html] view plaincopyprint?

<span style="font-size:14px;">#! /usr/bin/env python

# -*- coding: utf-8 -*-

# vim: tabstop=4 shiftwidth=4 softtabstop=4

def open(filename,mode):

import __builtin__

file = __builtin__.open(filename,mode)

if file.read(5) not in("GIF87", "GIF89"):

raise IOError, "not aGIF file"

file.seek(0)

return file

fp = open("sample/test.gif","r")

print len(fp.read()), "bytes"</span>

3. 重新实现str.strip(),注意不能使用string.*strip()

[html] view plaincopyprint?

<span style="font-size:14px;">#! /usr/bin/env python

# -*- coding: utf-8 -*-

# vim: tabstop=4 shiftwidth=4 softtabstop=4

# TODO rstrip

def rightStr(string,split=' '):

endind = string.rfind(split)

res = string

while endind != -1 and endind == len(res)-1:

res = res[:endind]

endind = res.rfind(split)

return res

# TODO lstrip

def leftStr(string,split=' '):

startind = string.find(split)

res = string

while startind != -1 and startind == 0:

res = res[startind+1:]

startind=res.find(split)

return res

def main():

word='aa asdf aa '

stripstr=' '

lenth = len(word)

res=word

# leftstrip

if word[0] == stripstr:

res=leftStr(res)

# rightstrip

if word[len(word)-1] == stripstr:

res=rightStr(res)

print res

if __name__ == "__main__":

main()

</span>

4. 说明os,sys模块不同,并列举常用的模块方法?

官方解释:
os: This module provides a portable way of using operating system dependent functionality.
翻译:提供一种方便的使用操作系统函数的方法。
sys:This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
翻译:提供访问由解释器使用或维护的变量和在与解释器交互使用到的函数。
os 常用方法

[html] view plaincopyprint?

os.remove()删除文件

os.rename()重命名文件

os.walk()生成目录树下的所有文件名

os.chdir()改变目录

os.mkdir/makedirs创建目录/多层目录

os.rmdir/removedirs删除目录/多层目录

os.listdir()列出指定目录的文件

os.getcwd()取得当前工作目录

os.chmod()改变目录权限

os.path.basename()去掉目录路径,返回文件名

os.path.dirname()去掉文件名,返回目录路径

os.path.join()将分离的各部分组合成一个路径名

os.path.split()返回(dirname(),basename())元组

os.path.splitext()(返回filename,extension)元组

os.path.getatime\ctime\mtime分别返回最近访问、创建、修改时间

os.path.getsize()返回文件大小

os.path.exists()是否存在

os.path.isabs()是否为绝对路径

os.path.isdir()是否为目录

os.path.isfile()是否为文件

sys 常用方法

[html] view plaincopyprint?

sys.argv 命令行参数List,第一个元素是程序本身路径

sys.modules.keys() 返回所有已经导入的模块列表

sys.exc_info() 获取当前正在处理的异常类,exc_type、exc_value、exc_traceback当前处理的异常详细信息

sys.exit(n) 退出程序,正常退出时exit(0)

sys.hexversion 获取Python解释程序的版本值,16进制格式如:0x020403F0

sys.version 获取Python解释程序的版本信息

sys.maxint 最大的Int值

sys.maxunicode 最大的Unicode值

sys.modules 返回系统导入的模块字段,key是模块名,value是模块

sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

sys.platform 返回操作系统平台名称

sys.stdout 标准输出

sys.stdin 标准输入

sys.stderr 错误输出

sys.exc_clear() 用来清除当前线程所出现的当前的或最近的错误信息

sys.exec_prefix 返回平台独立的python文件安装的位置

sys.byteorder 本地字节规则的指示器,big-endian平台的值是'big',little-endian平台的值是'little'

sys.copyright 记录python版权相关的东西

sys.api_version 解释器的C的API版本

sys.version_info

5. deepcopy 和 copy的区别?

copy 仅拷贝对象本身,而不拷贝对象中引用的其它对象。

deepcopy 除拷贝对象本身,而且拷贝对象中引用的其它对象。

例如:

[html] view plaincopyprint?

#! /usr/bin/env python

# -*- coding: utf-8 -*-

# vim: tabstop=4 shiftwidth=4 softtabstop=4

import copy

al = [[1],[2],[3]]

bl = copy.copy(al)

cl = copy.deepcopy(al)

print "before=>"

print al

print bl

print cl

al[0][0] = 0

al[1] = None

print "after=>"

print al

print bl

print cl

6. os.path和sys.path的区别?

os.path是module,包含了各种处理长文件名(路径名)的函数。

例如:

[html] view plaincopyprint?

#! /usr/bin/env python

# -*- coding: utf-8 -*-

# vim: tabstop=4 shiftwidth=4 softtabstop=4

import os

filename = "my/little/pony"

print "using", os.name, "..."

print "split", "=>", os.path.split(filename)

print "splitext", "=>", os.path.splitext(filename)

print "dirname", "=>", os.path.dirname(filename)

print "basename", "=>", os.path.basename(filename)

sys.path是由目录名构成的列表,Python 从中查找扩展模块( Python 源模块, 编译模块,或者二进制扩展). 启动 Python 时,这个列表从根据内建规则,PYTHONPATH 环境变量的内容, 以及注册表( Windows 系统)等进行初始化.

7. re模块中match和search方法的不同?

match() 函数只检查 RE 是否在字符串开始处匹配,而 search() 则是扫描整个字符串。

8. 如何匹配<html><title></title></html>得到<html>

[html] view plaincopyprint?

>>> import re

>>> str = r'<html><title></title></html>'

>>> p = re.compile(r'<.*?>')

>>> print p.match(str).group(0)

9. 重新实现filter,map,reduce。

[html] view plaincopyprint?

#! /usr/bin/env python

# -*- coding: utf-8 -*-

# vim: tabstop=4 shiftwidth=4 softtabstop=4

def filter_impl(func, argvs):

res = []

for argv in argvs:

if func(argv):

res.append(argv)

return res

# check filter impl

print "filter ==>"

print filter_impl(lambda x: x<4, range(1,10))

print filter(lambda x: x<4, range(1,10))

def map_impl(func, argvs):

res = []

for argv in argvs:

res.append(func(argv))

return res

# check map impl

print "map ==>"

print map_impl(lambda x: x*10, range(1,5))

print map(lambda x: x*10, range(1,5))

def reduce_impl(func, argvs, startVal=None):

if startVal is not None:

argv1 = startVal

else:

argv1 = argvs[0]

for argv2 in argvs[1:]:

argv1 = func(argv1, argv2)

return argv1

# check reduce impl

print "reduce ==>"

print reduce_impl(lambda x,y: x*y, range(1,4),20)

print reduce(lambda x,y: x*y, range(1,4),20)

Result:

filter ==>
[1, 2, 3]
[1, 2, 3]
map ==>
[10, 20, 30, 40]
[10, 20, 30, 40]
reduce ==>
120
120

10. 解释生成器(generator)与函数的不同,并实现和使用简单generator?

生成器和函数的主要区别在于函数 return a value,生成器 yield a value同时标记或记忆 point of the yield 以便于在下次调用时从标记点恢复执行。 yield 使函数转换成生成器,而生成器反过来又返回迭代器。

[html] view plaincopyprint?

#! /usr/bin/env python

# -*- coding: utf-8 -*-

# vim: tabstop=4 shiftwidth=4 softtabstop=4

def gem():

yield "first"

yield "second"

yield "third"

for res in gem():

print res

11. 设计实现遍历目录与子目录,抓取.pyc文件?

[html] view plaincopyprint?

#! /usr/bin/env python

# -*- coding: utf-8 -*-

# vim: tabstop=4 shiftwidth=4 softtabstop=4

# 1. for-in dir/subdir to get the filesname

# 2. splitext filename to filter

import os

def getFiles(dir, suffix):

res = []

for root,directory,files in os.walk(dir):

for filename in files:

name, suf = os.path.splitext(filename)

if suf == suffix:

res.append(os.path.join(root, filename))

return res

for file in getFiles("./", '.py'):

print file
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: