Home > Enterprise >  Checking the length of an attribute of a class for validation
Checking the length of an attribute of a class for validation

Time:02-05

In the below code, when creating the object circle in the last line, I want to validate that the center has only 2 elements in the list. The below code gives an error 'object of type 'Point' has no len()'. How do I correctly validate the attribute?

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)

CodePudding user response:

You are making Circle do too much work. If its center attribute is supposed to be a Point, a Point should be passed as an argument. Let the caller worry about creating a Point from a list of two values, and let Point worry about validating the construction of an instance of itself.

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)

If you really want something to create a point from a list of values, add a class method to 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)
  •  Tags:  
  • Related