第21条-用只能以关键字形式指定的参数来确保代码明晰
关键字参数可以通过位置参数传参
问题: 1 函数是如何接受参数的 ?
def safe_division(
number, divisor,
ignore_overflow=False,
ignore_zero_division=False):
try:
print('no error')
return number / divisor
except OverflowError:
print('ignore_overflow is {}'.format(ignore_overflow))
if ignore_overflow:
return 0
else:
print('OverflowError')
# raise
except ZeroDivisionError:
print('ignore_zero_division is {}'.format(ignore_zero_division))
if ignore_zero_division:
return float('inf')
else:
print('ZeroDivisionError')
# raise
# pass
print(safe_division(1, 10 ** 500, False, False))
print('==========')
print(safe_division(1, 10 ** 500, True, False))
print('==========')
print(safe_division(1, 0, True, True))
print('==========')
print(safe_division(1, 0, True, False))
print('==========')
# no error
# 0.0
# ==========
# no error
# 0.0
# ==========
# no error
# ignore_zero_division is True
# inf
# ==========
# no error
# ignore_zero_division is False
# ZeroDivisionError
# None
# ==========
# no error
# ignore_zero_division is True
# inf
以上写法存在的弊端为:函数定义了关键字参数,但是均可以通过位置参数与关键子参数传参,而位置参数容易导致传参错误
改进方向:必须以关键字的方式传参
#PYHTON2
def safe_division(number, divisor, **kwargs):
ignore_overflow = kwargs.pop('ignore_overflow', False)
ignore_zero_div = kwargs.pop('ignore_zero_division', False)
if kwargs:
raise TypeError('Unexpected **kwargs: %r' % kwargs)
try:
return number / divisor
except OverflowError:
if ignore_overflow:
return 0
else:
return 'OverflowError'
# raise
except ZeroDivisionError:
if ignore_zero_div:
return float('inf')
else:
return 'ZeroDivisionError'
# raise
print(safe_division(1, 0, ignore_overflow=True, ignore_zero_division=True))
# inf
print(safe_division(1, 10 ** 500, True, False))
# TypeError: safe_division() takes 2 positional arguments but 4 were given
#PYTHON3
# 星号 位置参数的结束标志
def safe_division(
number, divisor, *,
ignore_overflow=False,
ignore_zero_division=False):
try:
return number / divisor
except OverflowError:
if ignore_overflow:
return 0
else:
return 'OverflowError'
# raise
except ZeroDivisionError:
if ignore_zero_division:
return float('inf')
else:
return 'ZeroDivisionError'
# raise
print(safe_division(1, 0, ignore_overflow=True, ignore_zero_division=True))
# output:
# inf
print(safe_division(1, 10 ** 500, True, False))
# output
# TypeError: safe_division() takes 2 positional arguments but 4 were given
原文地址:https://www.cnblogs.com/max520liuhu/p/12046029.html
时间: 2024-10-22 05:03:23