【问题标题】:Python assert isinstance() VectorPython 断言 isinstance() 向量
【发布时间】: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


    【解决方案1】:

    assert 更适合用于调试,而不是在生产代码中闲逛。当传递的值不是所需类型时,您可以改为为矢量属性 xyzraise ValueError 创建属性:

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

    【讨论】:

    • 那么在那个例子中你也可以使用 isinstance() 而不仅仅是期望正确的类型吗?
    • @StefanB 可以,防止用户传递其他数字类型,例如复杂类型。
    猜你喜欢
    • 2018-08-29
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多