【发布时间】:2017-11-13 15:40:41
【问题描述】:
我正在尝试在 python 中实现 Vector3 类。如果我用 c++ 或 c# 编写 Vector3 类,我会将 X、Y 和 Z 成员存储为浮点数,但在 python 中,我读到鸭式是要走的路。所以根据我的 c++/c# 知识,我写了这样的东西:
class Vector3:
def __init__(self, x=0.0, y=0.0, z=0.0):
assert (isinstance(x, float) or isinstance(x, int)) and (isinstance(y, float) or isinstance(y, int)) and \
(isinstance(z, float) or isinstance(z, int))
self.x = float(x)
self.y = float(y)
self.z = float(z)
问题与断言语句有关:在这种情况下您会使用它们还是不使用它们(用于数学的 Vector3 实现)。我也将它用于诸如
之类的操作def __add__(self, other):
assert isinstance(other, Vector3)
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)
你会在这些情况下使用断言吗? 根据这个网站:https://wiki.python.org/moin/UsingAssertionsEffectively 它不应该被过度使用,但对于我作为一个一直使用静态类型的人来说,不检查相同的数据类型是非常奇怪的。
【问题讨论】:
标签: python assert duck-typing isinstance