va a fallar si la calveclave no está en el diccionario, si esto ocurre get
retorna "Invalid Argument"
, por lo que en la siguiente línea intentas llamar a una cadena:
class Robot:
def __init__(self, x, y):
self.x = x
self.y = y
self._switcher = {
"le": self.move_left,
"ri": self.move_right,
"up": self.move_up,
"do": self.move_down,
}
@property
def x(self):
return self._x
@x.setter
def x(self, x_value):
if not 1 <= x_value <= 5:
raise ValueError("x must be betwenbetween 1 and 5 (both included)")
self._x = x_value
@property
def y(self):
return self._y
@y.setter
def y(self, y_value):
if not 1 <= y_value <= 5:
raise ValueError("y must be between 1 and 5 (both included)")
self._y = y_value
def move_left(self):
if (self._x == 1):
return "You are in the left limit"
else:
self._x -= 1
return "({},{})".format(self._x, self._y)
def move_right(self):
if (self._x == 5):
return "You are in the rigth limit"
else:
self._x += 1
return "({},{})".format(self._x, self._y)
def move_up(self):
if (self._y == 1):
return "You are in the up limit"
else:
self._y -= 1
return "({},{})".format(self._x, self._y)
def move_down(self):
if (self._y == 5):
return "You are in the down limit"
else:
self._y += 1
return "({},{})".format(self._x, self._y)
def move(self, argumen):
func = self._switcher.get(argumen)
if func is None:
return "Invalid Argument"
return func()
def main():
player = Robot(1, 1)
print(player.move("ri"))
print(player.move("ri"))
print(player.move("ri"))
print(player.move("ri"))
print(player.move("ri"))
print(player.move("do"))
print(player.move("up"))
print(player.move("up"))
print(player.move("le"))
print(player.move("fo"))
player2 = Robot(6, 1)
if __name__ == "__main__":
main()
He añadido un par de properties para validar x
e y
en la instanciación y asegurarse que están entre 1 y 5.
(2,1) (3,1) (4,1) (5,1) You are in the rigth limit (5,2) (5,1) You are in the up limit (4,1) Invalid Argument Traceback (most recent call last): File "test.py", line 84, in <module> main() File "test.py", line 81, in main player2 = Robot(6, 1) File "test.py", line 4, in __init__ self.x = x File "test.py", line 20, in x raise ValueError("x must be betwenbetween 1 and 5 (both included)") ValueError: x must be betwen 1 and 5 (both included)