使用装饰器在Python中处理错误
PythonPython的最有用的概念之一。它接受函数作为参数并且还有一个嵌套函数。它们扩展了嵌套函数的功能。
例子:
Python3
# defining decorator function
def decorator_example(func):
print("Decorator called")
# defining inner decorator function
def inner_function():
print("inner function")
func()
return inner_function
# defining outer decorator function
@decorator_example
def out_function():
print("outer function")
out_function()
Python3
def mean(a,b):
try:
print((a+b)/2)
except TypeError:
print("wrong data types. enter numeric")
def square(sq):
try:
print(sq*sq)
except TypeError:
print("wrong data types. enter numeric")
def divide(l,b):
try:
print(b/l)
except TypeError:
print("wrong data types. enter numeric")
mean(4,5)
square(21)
divide(8,4)
divide("two","one")
Python3
def Error_Handler(func):
def Inner_Function(*args, **kwargs):
try:
func(*args, **kwargs)
except TypeError:
print(f"{func.__name__} wrong data types. enter numeric")
return Inner_Function
@Error_Handler
def Mean(a,b):
print((a+b)/2)
@Error_Handler
def Square(sq):
print(sq*sq)
@Error_Handler
def Divide(l,b):
print(b/l)
Mean(4,5)
Square(14)
Divide(8,4)
Square("three")
Divide("two","one")
Mean("six","five")
输出:
Decorator called
inner function
outer function
使用装饰器处理错误
以下示例显示了不使用任何装饰器的一般错误处理代码的样子:
蟒蛇3
def mean(a,b):
try:
print((a+b)/2)
except TypeError:
print("wrong data types. enter numeric")
def square(sq):
try:
print(sq*sq)
except TypeError:
print("wrong data types. enter numeric")
def divide(l,b):
try:
print(b/l)
except TypeError:
print("wrong data types. enter numeric")
mean(4,5)
square(21)
divide(8,4)
divide("two","one")
输出 :
4.5
441
0.5
wrong data types. enter numeric
即使上面的代码在逻辑上没有任何错误,但它缺乏清晰度。为了使代码更干净和高效,装饰器用于错误处理。下面的示例描述了如何通过使用装饰器使上述代码更易于理解:
蟒蛇3
def Error_Handler(func):
def Inner_Function(*args, **kwargs):
try:
func(*args, **kwargs)
except TypeError:
print(f"{func.__name__} wrong data types. enter numeric")
return Inner_Function
@Error_Handler
def Mean(a,b):
print((a+b)/2)
@Error_Handler
def Square(sq):
print(sq*sq)
@Error_Handler
def Divide(l,b):
print(b/l)
Mean(4,5)
Square(14)
Divide(8,4)
Square("three")
Divide("two","one")
Mean("six","five")
输出 :
4.5
196
0.5
Square wrong data types. enter numeric
Divide wrong data types. enter numeric
Mean wrong data types. enter numeric