我对Python和编程完全陌生,所以我不太熟悉良好的实践或以最充分/清晰的方式编写代码。我已经为一些数学运算编写了这个函数,我希望Python能够处理一些异常。
def sqrt_of_sum_by_product(numbers: tuple) -> float:
if prod(numbers) <= 0: # checking if the result is a positive num to prevent further operations
raise ValueError('cannot find sqrt of a negative number or divide by 0')
return float("{:.3f}".format(math.sqrt(sum(numbers) / prod(numbers))))
这个代码有效,我认为它足够清楚,但我不确定像我那样提出异常是否是一个好的做法,我找不到答案。
是的,这是一个很好的做法,但有时您可能想要创建自己的错误。例如:
class MyExeption(Exception):
_code = None
_message = None
def __init__(self, message=None, code=None):
self._code = message
self._message = code
现在你可以做:
def sqrt_of_sum_by_product(numbers: tuple) -> float:
if prod(numbers) <= 0: # checking if the result is a positive num to prevent further operations
raise MyExeption('cannot find sqrt of a negative number or divide by 0', 'XXX')
return float("{:.3f}".format(math.sqrt(sum(numbers) / prod(numbers))))
我认为以这种方式引发异常是一种很好的做法。您也可以使用try/except来实际获取异常,然后进行处理。我不会质疑您对代码的使用。