工厂模式
两个类A和B之间的关系应该仅仅是A创建B或 是A使用B,而不能两种关系都有
将对象的创建和使用分离,也使得系统更加符合“单一职责原则”,有利于对功能的复用和系统的维护
防止用来实例化一个类的数据和代码在多个类中到处都是
'''
除下实现方式外,还对以对工厂进一步进行抽象,得到抽象工厂,使得进一步解耦,
不再通过参数来得到要生产的类的对象。
'''
class Fruit:
pass
class Apple(Fruit):
pass
def pie(self):
print("making apple pie")
class Orange(Fruit):
pass
def juice(self):
print("making orange juice")
class FruitFactory:
def generate_fruit(self,type):
if type=='a':
return Apple() #可以根据apple的定义进行初始化
elif type=='o':
return Orange()#可以根据orange的定义进行初始化
else:
return None
ff=FruitFactory()
apple=ff.generate_fruit('a')
orange=ff.generate_fruit('o')
apple.pie()
orange.juice()
#“抽象”工厂的简要实现
class Factory:
def generate(self):
pass
class AppleFactory(Factory):
def generate(self):
return Apple()#
class OrangeFactory(Factory):
def generate(self):
return Orange()
异常处理
- 异常捕获
try:
<statements>
except;
<statements>
执行try子句,无异常发生时except子句被忽略。
包含多个except子句时最多只有一个分支会被执行。
class AccoutError(Exception):
def __init__(self,user):
self.user=user
class AccountNegativeDepositError(AccoutError):
def __init__(self,user,m):
self.user=user
self.m=m
self.message="{} deposit negative amount: {}".format(user,m)
class AccountBalanceNotEnoughError(AccoutError):
def __init__(self,user,balance, m):
self.user=user
self.m=m
self.balance=balance
self.message="{}'s balance {} is smaller than the withdraw amount of {}. Loan is suggested.".format(user,balance,m)
class Account:
def __init__(self,user,balance):
self._user=user
self._balance=balance
def set_balance(self,balance):
self._balance=balance
def get_balance(self):
return self._balance
def get_user(self):
return self._user
def deposit(self,m):
if m<0:
raise AccountNegativeDepositError(self.get_user(),m)
else:
self.set_balance(self.get_balance()+m)
def withdraw(self,m):
if self.get_balance()<m:
raise AccountBalanceNotEnoughError(self.get_user(),self.get_balance(),m)
else:
self.set_balance(self.get_balance()-m)
account=Account('zjc',100)
try:
#account.deposit(-100)
account.withdraw(10000)
except AccountNegativeDepositError as ande:
print(ande.message)
except AccountBalanceNotEnoughError as abnee:
print(abnee.message)
except AccoutError:
print('noname exception')
else:
print('no except...')
print(account.get_balance())
- 定义清理行为
无论try子句有无发生异常,finally子句都会执行
try:
result = x/y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is",result)
finally:
print("executing finally clause")
-
return语句的位置
不要在try, except, else
子句里写返回值。
尤其是有else子句时,try中的return会导致else不执行
如果finally有返回值,其将会覆盖原始的返回值 -
断言
用于判断一个表达式,并在表达式False的时候触发异常
#assert expression
if not expression:
raise AssertionError
#assert expression [,arguments]
if not expression:
raise AssertionError(arguments)
网友评论