class 中的变量类型:最佳编程实践

Type of variables in a class: best programming practices

我定义了一个class如下:

import numpy as np

class Vector:
    def __init__(self, v):
        self.v = v

我可以通过执行以下操作创建 class 的实例:

p1 = np.array([0.0, 0.0, 0.0])

v1 = Vector(p1)
v2 = Vector(3)

我的意图是 Vector 总是包含一个 3D 向量 space。但是,python 中确保 Vector 始终是 3 分量向量的正确方法是什么?

有两种方式可以同时使用。首先,在运行时:

class Vector:
    def __init__(self, v):
        if not isinstance(v, np.ndarray) or v.shape != (3,):
            raise ValueError("vector must be 3-dimensional array")
        self.v = v

像这样检查类型几乎是 python 中的标准约定。然而,随着 Python 3.5+ 添加了 typing 模块,它允许所谓的 "type hints",它可以通过你的 IDE 或 linter 进行静态分析:

class Vector:
    def __init__(self, v: np.ndarray[float, shape=(3,)]):
        self.v = v

但是,numpy 的类型提示尚未完全实现(以上语法是初步的),请参阅 this tracking issue on GitHub

不确定这是否是最好的方法,但肯定是一种方法。 您可以通过以下代码查看:

import numpy as np
class Vector:
    def __init__(self, v):
        if isinstance(v, np.ndarray)  and v.size == 3:
            self.v = v
        else:
            raise ValueError('param is not an Array in the 3D space')