簡體   English   中英

Python assert isinstance() 向量

[英]Python assert isinstance() Vector

我正在嘗試在 python 中實現一個 Vector3 類。 如果我用 c++ 或 c# 編寫 Vector3 類,我會將 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)

問題是關於斷言語句:在這種情況下你會使用它們還是不使用它們(數學的 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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM