我正在使用 Python,每当我必须验证函数输入时,我都会假设输入有效,然后捕获错误。
就我而言,我有一个通用的Vector()
我用它来做一些不同的事情,其中之一就是加法。它的功能既是Color()
类并作为Vector()
,所以当我向Color()
,它应该将该常数添加到每个单独的组件中。Vector()
and Vector()
添加需要按组件添加。
该代码用于光线追踪器,因此任何速度提升都很棒。
这是我的简化版本Vector()
class:
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
try:
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
except AttributeError:
return Vector(self.x + other, self.y + other, self.z + other)
我目前正在使用try...except
方法。有人知道更快的方法吗?
EDIT:感谢这些答案,我尝试并测试了以下解决方案,该解决方案在添加之前专门检查类名Vector()
对象:
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
if type(self) == type(other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
else:
return Vector(self.x + other, self.y + other, self.z + other)
我使用这两个代码块进行了速度测试timeit http://docs.python.org/library/timeit.html,结果非常显着:
1.0528049469 usec/pass for Try...Except
0.732456922531 usec/pass for If...Else
Ratio (first / second): 1.43736090753
我还没有测试过Vector()
与 一起上课no无论如何输入验证(即将检查移出类并移至实际代码中),但我想它甚至比if...else
method.
更新较晚: 回头看这段代码,这是not一个最优解。
OOP 使这变得更快:
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
class Color(Vector):
def __add__(self, other):
if type(self) == type(other):
return Color(self.x + other.x, self.y + other.y, self.z + other.z)
else:
return Color(self.x + other, self.y + other, self.z + other)