关卡二:
1.练习题1:设计模式
练习使用单例模式。
参考课件,使用工厂模式实现苹果电脑专卖店。
参考代码:
# 定义一个基本的电脑专卖店类
class ComputerStore(object):
#仅仅是定义了这个方法,并没有实现,具体功能,这个需要在子类中实现
def createComputer(self, typeName):
pass
def order(self, typeName):
# 让工厂根据类型,生产一台电脑
self.computer = self.createComputer(typeName)
self.computer.movie()
self.computer.program()
# 定义一个苹果专卖店类
class AppleStore(ComputerStore):
def createComputer(self, typeName):
self.computerFactory = ComputerFactory()
return self.computerFactory.createComputer(typeName)
# 定义Mac类
class MacComputer(object):
# 定义电脑的方法
def movie(self):
print("---使用Mac播放电影---")
def program(self):
print("---使用Mac编程---")
# 定义Air类
class AirComputer(object):
# 定义电脑的方法
def movie(self):
print("---使用Air播放电影---")
def program(self):
print("---使用Air编程---")
# 定义一个生产电脑的工厂,让其根据具体得订单生产电脑
class ComputerFactory(object):
def createComputer(self,typeName):
self.typeName = typeName
if self.typeName == "Mac":
self.computer = MacComputer()
elif self.typeName == "Air":
self.computer = AirComputer()
return self.computer
computer = AppleStore()
computer.order("Mac")
2.练习题2:异常
编写一段代码展示python中try…except…else…finally的执行顺序
参考代码:
print('this is a test of code path in try...except...else...finally')
print('************************************************************')
def exceptTest():
try:
print('doing some work, and maybe exception will be raised')
raise IndexError('index error')
except IndexError as result:
print('in IndexError except: ', result) #捕获异常并输出异常信息
else:
print('no exception') #若捕获不到异常执行此段代码
finally:
print('in finally') #无论异常是否捕获都执行此段代码
resultCode = exceptTest()
下面两段Python代码(a)和(b)有什么区别?考虑语句的上下文环境。
(a)
try:
test1
except …:
…
else:
test2
(b)
try:
test1
test2
except …:
…
1.如果test1执行出错,则(a)和(b)都不会执行test2;
2.如果test1执行正常,则(a)和(b)都会执行test2,
但是,如果test2的执行也出错,(b)可以在except子句里捕获到异常并做处理,
而(a)则只能将test2产生的异常抛给上层调用者。
3.练习题3:模块
导入random模块, 生成0-100间所有数字的随机列表(列表中的数字不重复)。
参考代码:
import random
li = []
while len(li) < 100:
n = random.randint(1, 100)
if n not in li:
li.append(n)
print(li, end='')