未正确处理点值

Point values not being handled correctly

我有一个 PointND class 表示 N 维 space 中的一个点(如下所示)。

class PointND:
    """
    Class to represent an N-dimensional point.
    """
    def __init__(self, *vals):
        if len(vals) == 1 and isinstance(vals, list):
            self.vals = vals[0]
        else:
            self.vals = vals
        self.point = []
        self.dimensions = len(self.vals)
        for i in self.vals:
            self.point.append(i)

当我给它一系列输入时,它工作正常(例如:PointND(1, 2, 3, 4))。但是,每当我给它一个输入列表(例如:PointND([1, 2, 3, 4]))时,它就会中断。

我将 __repr__ 函数定义为:

def __repr__(self):
        __a = f"{self.dimensions}D Point: ({self.vals[0]}"
        for i in range(1, len(self.vals)):
            __a = f"{__a}, {self.vals[i]}"
        __a = f"{__a})"
        return __a

当我执行 print(PointND(1, 2, 3, 4, 5)) 时,它输出:

> 4D Point: (1, 2, 3, 4)

然而,当我简单地将其更改为:print(PointND([1, 2, 3, 4, 5])),它输出:

> 1D Point: ([1, 2, 3, 4])

我不知道为什么会这样,但是如果有人知道 and/or 有解决办法,请告诉我!

这里你可能是想检查 vals[0] 的类型,而不是 vals.

    def __init__(self, *vals):
-       if len(vals) == 1 and isinstance(vals, list):
+       if len(vals) == 1 and isinstance(vals[0], list):
            self.vals = vals[0]
        else:
            self.vals = vals

(vals 永远不会是一个列表,它永远是一个元组)

我认为这是一个糟糕的界面:它让您可以用两种不同的方式表达同一件事。我会选择一种创建点的方法:

# a) accept varargs
    def __init__(self, *vals):
        self.point = list(vals)
        self.dimensions = len(vals)

# b) accept a list (or any iterable, really)
    def __init__(self, vals):
        self.point = list(vals)
        self.dimensions = len(vals)