一、本題考點在於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
'''
