Python 断言 isinstance() 向量

标签 python assert duck-typing isinstance

我正在尝试在 python 中实现 Vector3 类。如果我用 c++ 或 c# 编写 Vector3 类,我会将 X、Y 和 Z 成员存储为 float ,但在 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它不应该被过度使用,但对于我作为一个一直使用静态类型的人来说,不检查相同的数据类型是非常奇怪的。

最佳答案

assert 比在生产代码中闲逛更适合用于调试。您可以改为为矢量属性 xyz 以及 raise ValueError< 创建属性/strong> 当传递的值不是所需的类型时:

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)))
    ...

关于Python 断言 isinstance() 向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47268107/

相关文章:

Java断言错误不抛出错误

c# - C#和Java是鸭子类型(duck typing)的吗?

python - Python 中的通用类工厂

python - 导入错误 : cannot import name add_newdocs

Python pytest 不显示断言差异

testing - 断言失败。无法确定原因?

python - 如何反转正则表达式替换?

python - Pandas:IndexingError:不可对齐的 bool 系列作为索引器提供

python : using type hints to dynamically check types

algorithm - 处理网络数据结构方法的 Pythonic 方式