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之前检查文件格式?
#! /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"
3. 重新实现str.strip(),注意不能使用string.*strip()
#! /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 start