Created
October 16, 2018 11:05
-
-
Save devxpy/735c4823ca65e516d65427a05f123078 to your computer and use it in GitHub Desktop.
The toy robot problem, using python decorators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def pos_safe(fn): | |
def wrapper(self): | |
old = self._pos.copy() | |
fn(self) | |
for i in range(2): | |
if not (0 <= self._pos[i] <= self.bounds[i]): | |
self._pos = old | |
raise ValueError("Robot shall not pass!") | |
self.curpos() | |
return wrapper | |
class Robot: | |
_pos = [0, 0] | |
def __init__(self, bounds=(5, 5)): | |
self.bounds = bounds | |
def curpos(self): | |
print("Robot positon:", self._pos) | |
@pos_safe | |
def right(self): | |
self._pos[0] += 1 | |
@pos_safe | |
def left(self): | |
self._pos[0] -= 1 | |
@pos_safe | |
def up(self): | |
self._pos[1] += 1 | |
@pos_safe | |
def down(self): | |
self._pos[1] -= 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment