拓展原来函数功能的函数
返回函数的函数
在不用更改原来函数的代码的前提下给函数增加新功能
def hello(): print("hello") def add(): print("begin........") hello() print("end..........") add() Result: begin........ hello end.......... ######################### def add(func): def result(): print("begin........") func() print("end..........") # return return result @add # 定义一个装饰器,传入hello()函数到add(func)函数并作 def hello(): # 为参数func,在add()函数中定义一个函数并返回,调用 print("hello") # hello()函数得到的即为返回函数 # return hello() Result: begin........ hello end..........为类进行扩充
def introduce(cls): cls.hello=lambda self:print("hello......") return cls @introduce class People: pass people=People() people.hello() --> hello......异常是一个类
异常不被捕获就会终止程序
内置异常类
类名描述Exception几乎所有异常类都是它派生AttributeError引用属性或给它赋值失败是引起OSError操作系统不能执行指定的任务时引起,有多个子类IndexError使用序列中不存在的索引时引起,为LookuoError的子类KeyError使用映射中不存在的键时引起,为LookuoError的子类NameError找不到名称(变量)时引起SyntaxError代码不正确时引发TypeError将内置操作或函数用于类型不正确的对象时引发ValueError将内置操作或函数用于这样的对象时引发:其类型正确但包含的值不合适ZeroDivisionError在除法或求模运算的第二个参数为0时引发try.......except(....) as name....finally...
# 1 try: 5/0 except: print("wrong") Result: wrong # 2 try: 5/0 except(ZeroDivisionError,TypeError): print("wrong") Result: wrong # 3 try: 5/"s" except(ZeroDivisionError) as e: print(e) except(TypeError) as e: print(e) Result: unsupported operand type(s) for /: 'int' and 'str' # 4 try: file=open('hello.txt') read=file.read() except(FileNotFoundError) as e: print("wrong") print(e) finally: try: file.close() except: print("ok") Result: wrong [Errno 2] No such file or directory: 'hello.txt' ok自定义异常继承自Exception
触发利用 raise exception_name
class MyException(Exception): def __init__(self,err_code,err_msg): self.err_code=err_code self.err_msg=err_msg def __str__(self): return "MyException:{}---{}".format(self.err_code,self.msg) raise MyException(101,"myexception") Result: Traceback (most recent call last): File "D:/study/python/MyTest/test.py", line 8, in <module> raise MyException(101,"myexception") __main__.MyException: <exception str() failed> ######################################## try: raise MyException(101, "myexception") except(MyException) as e: print(e) Result: MyException:101---myexception