Python 断言 isinstance() 向量

Python assert isinstance() Vector

我正在尝试在 python 中实现 Vector3 class。如果我用 C++ 或 C# 编写 Vector3 class,我会将 X、Y 和 Z 成员存储为浮点数,但在 python 中,我读到 ducktyping 是可行的方法。所以根据我的 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)

问题是关于 assert 语句的:在这种情况下你会不会使用它们(数学的 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 它不应该被过度使用,但对于我这个一直使用静态类型的人来说,不检查相同的数据类型是非常奇怪的。

assert 比在生产代码中闲逛更好地用于调试。当传递的值不是所需类型:

class Vector3:
    def __init__(self, x=0.0, y=0.0, z=0.0):
        self.x = x
        self.y = y
        self.z = z

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, val):
        if not isinstance(val, (int, float)):
            raise TypeError('Inappropriate type: {} for x whereas a float \
            or int is expected'.format(type(val)))
        self._x = float(val)

    ...

注意 isinstance 如何也采用类型元组。

__add__ 运算符中,您还需要 raise TypeError,包括适当的消息:

def __add__(self, other):
    if not isinstance(other, Vector3):
        raise TypeError('Object of type Vector3 expected, \
        however type {} was passed'.format(type(other)))
    ...