检查 class 的属性长度以进行验证

Checking the length of an attribute of a class for validation

在下面的代码中,当在最后一行创建对象圆时,我想验证中心在列表中只有 2 个元素。下面的代码给出了一个错误“'Point' 类型的对象没有 len()”。如何正确验证属性?

class Point():
    pass

class circle():
    def __init__(self,center, radius):
        self.center = center
        self.radius = radius
        self.center = Point()
        self.center.x = center[0]
        self.center.y = center[1]
            
    @property
    def center(self):
        return self._center

    @center.setter
    def center(self, d):
        if len(d)> 2:
            print('this is not a 2D point')
        else:
            self._center = d
        
circle = circle([150,100],75)

你让 Circle 做了太多的工作。如果它的 center 属性应该是 Point,那么 Point 应该作为参数传递。让调用者担心从两个值的列表创建 Point,让 Point 担心验证自身实例的构造。

class Point:
    def __init__(self, x: int, y: int):
        self.x = x
        self.y = y


class Circle:
    def __init__(self, center: Point, radius: int):
        self.center = center
        self.radius = radius


circle = Circle(Point(150, 100), 75)

如果您真的想要从值列表创建点,请将 class 方法添加到 Point:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    @classmethod
    def from_pair(self, p: Iterable[int]):
        try:
            x, y = p
        except ValueError:
            raise ValueError("Argument should contain exactly 2 values")

        return cls(x, y)


circle = Circle(Point.from_pair([150, 100]), 75)