Search code examples
pythonclassgetter-setter

how do i raise a value error in this. i am trying to do so but it wont just output


Create a class called Position that manages the position x and y.

Your constructor should take in the initial position of x and of y and upper limits for x and y and then use properties to manage x and y so that they cannot be set above these limits. Note you will need a property (getter/setter) for both x and y.

If an attempt to assign a value above the limit is made then it should raise a ValueError.

class Position:
  def __init__(self,x,y,z,value):
    self.x=x
    self.y=y
  pass

  @property
  def value(self):
    return f"{self._x} and {self._y}"

  @value.setter
  def name(self,value):
    self._x = value.upper()
    self._y = value.upper()
    if value > 10:
      raise ValueError("x cannot be bigger than 10")
    self._name = value
 

if __name__ == "__main__":
  p = Position(0,0,10,10) # x=0, y=0, 
  print(f"x={p.x} and y={p.y}") # prints x=0 and y=0
  p.x = 2
  print(f"x={p.x} and y={p.y}") # prints x=2 and y=0
  p.y += 3 
  print(f"x={p.x} and y={p.y}") # prints x=2 and y=3
  p.x = 11 # raises ValueError: x cannot be bigger than 10

Solution

  • If you want to validate each of x and y, you need to created @property and @_.setter for each one of them.

    class Position:
        def __init__(self, x, y):
            self._x = x  # private x
            self._y = y  # private y
    
        @property
        def x(self):
            return self._x
    
        @x.setter
        def x(self, x):
            if x > 10:
                raise ValueError("x cannot be bigger than 10")
            self._x = x
    
        @property
        def y(self):
            return self._y
    
        @y.setter
        def y(self, y):
            if y > 10:
                raise ValueError("y cannot be bigger than 10")
            self._y = y
    
    p1 = Position(11, 12)  # note no validation in __init__ func feel free to add it
    p1.x = 30  # raises ValueError("x cannot be bigger than 10")
    p1.x = 3  # OK
    

    NB. the property method, the _ in _.setter and the setter method must be named the same.