如前所述,python是duck类型的,因此您只需像平常一样做一些事情,并期望用户处理引发的任何异常。在
最好对代码进行单元测试,确保所有代码都使用有效的数字,这会增加您对某些工作的信心,并允许您更轻松地缩小可能的错误位置。在
如果您真的想检查类型,您可以使用对象类型上的断言(例如isinstance(direction, int))进行调试,但这实际上只是“穷人的单元测试”。在
使用python的原则(请求原谅,而不是许可,显式优于隐式,我会这样做:import math
def rotate_vector(vector, axis, direction):
try:
x, y, z = vector
except TypeError:
raise TypeError("Invalid vector {0}".format(vector))
valid_axes = {(1,0,0), (-1,0,0), (0,1,0), (0,-1,0), (0,0,1), (0,0,-1)}
if not axis in valid_axes:
raise ValueError("Invalid axis {0}".format(axis))
try:
ax, ay, az = axis
except TypeError:
raise TypeError("Invalid axis {0}".format(axis))
# do math to rotate the vector
# rotated = ...
try:
# You really only need the sign of the direction
return math.copysign(rotated, direction)
# or:
return rotated * math.copysign(1, direction)
except TypeError:
raise TypeError("Invalid direction {0}".format(direction))
既然你真的只关心方向的符号,你就可以使用它并消除对它的任何错误检查。特殊情况下的0将被视为1,您可能需要为它引发一个ValueError。在
如果您实际上不需要ax/ay/az或x/y/z,那么最好直接对vector和{}执行操作,并让底层操作引发异常。这将为duck类型启用它。在
编辑:(为问题中的新值更新了axes->;axis)