我正在尝试用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)问题是关于assert语句:在这个实例中使用还是不使用它们(数学的Vector3实现)。我还将它用于如下操作
def __add__(self, other):
assert isinstance(other, Vector3)
return Vector3(self.x + other.x, self.y + other.y, self.z + other.z)在这些情况下,您是否会使用assert?根据这个网站:https://wiki.python.org/moin/UsingAssertionsEffectively不应该被过度使用,但对于我来说,作为一个一直使用静态类型的人,不检查相同的数据类型是非常奇怪的。
发布于 2017-11-13 23:49:09
assert更适合用于调试,而不是在生产代码中游手好闲。当传递的值不是所需类型时,您可以为矢量属性raise ValueError、x、y和z创建属性:
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)))
...https://stackoverflow.com/questions/47268107
复制相似问题