一、本题考点在于with as的语法及使用,2个内置方法。
'''面试题,设计一个类Foo,使其满足一下代码输出
with Foo() as a:
print("2")
输出为:123 (每个整数数字为一行)
'''
class Foo():
def __enter__(self):
print(1)
def __exit__(self, exc_type, exc_val, exc_tb):
print(3)
with Foo() as a:
print("2")
'''
上下文管理器:在对象内实现了两个方法:__enter__()和__exit__()
__enter__()方法会在with的代码执行前执行
__exit__()方法会在代码块执行结束后执行。
'''
二、本题考点装饰器
'''
设计一个装饰器"addhttp",使其满足以下代码输出
@addhttp
def test():
return www.changyou.com
print(test) #输出为http://www.changyou.com
'''
def func(func):
def wrapper(*args,**kwargs):
return "http://%s"%func()
return wrapper
@func
def aa1():
return "www.changyou.com"
print(aa1())
三、考察正则及文件的使用。
'''
写一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数。
'''
import re
def func(parse,file):
'''parse是要搜索的字符串,file是被搜索的文件'''
f=open(file,'r')
res=f.read()
result=re.findall(parse,res)
print(result.count(parse))
func('I','abc.txt')
四、这道题暂时还没做出来。。。
'''
现有一个类Test,请设计一个Test的子类,TestChild,使如下断言成立
class Test(object):
pass
请设计子类TestChild
t=TestChild()
assert isinstance(t,int) is True
'''