【发布时间】:2011-08-01 03:57:01
【问题描述】:
我正在使用 Python,每当我必须验证函数输入时,我都会假设输入有效,然后发现错误。
就我而言,我有一个通用的Vector() 类,我用它来做一些不同的事情,其中之一就是加法。它既可以用作Color() 类,也可以用作Vector(),因此当我向Color() 添加标量时,它应该将该常量添加到每个单独的组件中。 Vector() 和 Vector() 添加需要按组件添加。
此代码用于光线追踪器,因此任何速度提升都很棒。
这是我的Vector() 类的简化版本:
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 方法。有人知道更快的方法吗?
编辑:感谢答案,我尝试并测试了以下解决方案,该解决方案在添加 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 对这两个代码块进行了速度测试,结果非常显着:
1.0528049469 usec/pass for Try...Except
0.732456922531 usec/pass for If...Else
Ratio (first / second): 1.43736090753
我还没有测试Vector() 类与no 输入验证(即将签出类并进入实际代码),但我想它会更快比if...else 方法。
延迟更新:回顾这段代码,这不是最佳解决方案。
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)
【问题讨论】:
-
请使用
timeit并附上您的两个备选方案的真实计时结果。 -
你知道这两个例子做不同的事情吗?由于它们不可比较,因此不清楚您测量的是什么。
-
我会发布我的代码。不要以为我在终端窗口中手动输入了
'a'1,000,000 次;) -
您的
if验证不适用于像“-1”这样的负数 -
@Blender:请关注这个问题。您的 if 'a'.isdigit() 完全不相关且令人困惑。请删除它。如果您的“真正”问题是您的
VectorCheck课程,那么就证明这一点。另外,不要乱用花哨的“line-out”和其他标记。 SO 维护一个完整的变更日志。请只关注一件事。将你的真实问题打包成其他人可以学习的东西。
标签: python performance exception-handling typechecking