|
| 1 | +from math import pi |
| 2 | + |
| 3 | + |
| 4 | +class TypeChecker: |
| 5 | + required_type = object |
| 6 | + |
| 7 | + def __init__(self, name=None): |
| 8 | + self.name = name |
| 9 | + |
| 10 | + def __get__(self, instance, owner=None): |
| 11 | + return instance.__dict__[self.name] |
| 12 | + |
| 13 | + def __set__(self, instance, value): |
| 14 | + assert isinstance(value, self.required_type), \ |
| 15 | + f'Booooo! Expecting a {self.required_type.__name__}' |
| 16 | + instance.__dict__[self.name] = value |
| 17 | + |
| 18 | + |
| 19 | +class IntType(TypeChecker): |
| 20 | + required_type = int |
| 21 | + |
| 22 | + |
| 23 | +def type_check(**kwargs): |
| 24 | + def wrapper(cls): |
| 25 | + for var_name, checker_class in kwargs.items(): |
| 26 | + setattr(cls, var_name, checker_class(var_name)) |
| 27 | + return cls |
| 28 | + return wrapper |
| 29 | + |
| 30 | + |
| 31 | +@type_check(x=IntType, y=IntType) |
| 32 | +class Point: |
| 33 | + def __init__(self, x, y): |
| 34 | + self.x = x |
| 35 | + self.y = y |
| 36 | + |
| 37 | + def move_by(self, dx, dy): |
| 38 | + self.x += dx |
| 39 | + self.y += dy |
| 40 | + |
| 41 | + def __str__(self): |
| 42 | + return f'A Point at {self.x}, {self.y}' |
| 43 | + |
| 44 | + def __repr__(self): |
| 45 | + return f'{self.__class__.__name__}({self.x}, {self.y})' |
| 46 | + |
| 47 | + |
| 48 | +class PointType(TypeChecker): |
| 49 | + required_type = Point |
| 50 | + |
| 51 | + |
| 52 | +@type_check(center=PointType, radius=IntType) |
| 53 | +class Circle: |
| 54 | + center = PointType('center') |
| 55 | + radius = IntType('radius') |
| 56 | + |
| 57 | + def __init__(self, center, radius): |
| 58 | + self.center = center |
| 59 | + self.radius = radius |
| 60 | + |
| 61 | + @property |
| 62 | + def area(self): |
| 63 | + return pi * self.radius ** 2 |
| 64 | + |
| 65 | + def __str__(self): |
| 66 | + return f'A Circle at {self.center.x}, {self.center.y} and ' + \ |
| 67 | + f'radius {self.radius}' |
| 68 | + |
| 69 | + def __repr__(self): |
| 70 | + return f'{self.__class__.__name__}({self.center!r}, {self.radius!r})' |
| 71 | + |
| 72 | + |
| 73 | +# Fewer lines of code! |
| 74 | +# Mind-bending? |
0 commit comments