|
| 1 | +from math import pi |
| 2 | + |
| 3 | + |
| 4 | +def check_type(name, required_type): |
| 5 | + variable_name = f'_{name}' |
| 6 | + |
| 7 | + @property |
| 8 | + def variable(self): |
| 9 | + return getattr(self, variable_name) |
| 10 | + |
| 11 | + @variable.setter |
| 12 | + def variable(self, value): |
| 13 | + assert isinstance(value, required_type), \ |
| 14 | + f'Booooo! Expecting a {required_type.__name__}' |
| 15 | + setattr(self, variable_name, value) |
| 16 | + return variable |
| 17 | + |
| 18 | + |
| 19 | +class Point: |
| 20 | + x = check_type('x', int) |
| 21 | + y = check_type('y', int) |
| 22 | + |
| 23 | + def __init__(self, x, y): |
| 24 | + self.x = x |
| 25 | + self.y = y |
| 26 | + |
| 27 | + def move_by(self, dx, dy): |
| 28 | + self.x += dx |
| 29 | + self.y += dy |
| 30 | + |
| 31 | + def __str__(self): |
| 32 | + return f'A Point at {self.x}, {self.y}' |
| 33 | + |
| 34 | + def __repr__(self): |
| 35 | + return f'{self.__class__.__name__}({self.x}, {self.y})' |
| 36 | + |
| 37 | + |
| 38 | +class Circle: |
| 39 | + center = check_type('center', Point) |
| 40 | + radius = check_type('radius', int) |
| 41 | + |
| 42 | + def __init__(self, center, radius): |
| 43 | + self.center = center |
| 44 | + self.radius = radius |
| 45 | + |
| 46 | + @property |
| 47 | + def area(self): |
| 48 | + return pi * self.radius ** 2 |
| 49 | + |
| 50 | + def __str__(self): |
| 51 | + return f'A Circle at {self.center.x}, {self.center.y} and ' + \ |
| 52 | + f'radius {self.radius}' |
| 53 | + |
| 54 | + def __repr__(self): |
| 55 | + return f'{self.__class__.__name__}({self.center!r}, {self.radius!r})' |
| 56 | + |
| 57 | + |
| 58 | +# Fewer lines of code! |
| 59 | +# Mind-bending? |
0 commit comments