|
| 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 | +def type_check(cls): |
| 20 | + for var_name, var_type in cls.__annotations__.items(): |
| 21 | + class Checker(TypeChecker): |
| 22 | + required_type = var_type |
| 23 | + |
| 24 | + setattr(cls, var_name, Checker(var_name)) |
| 25 | + return cls |
| 26 | + |
| 27 | + |
| 28 | +class TypeCheckMeta(type): |
| 29 | + def __new__(meta, name, bases, dct): |
| 30 | + cls = super().__new__(meta, name, bases, dct) |
| 31 | + return type_check(cls) |
| 32 | + |
| 33 | + |
| 34 | +class Base(metaclass=TypeCheckMeta): |
| 35 | + __annotations__ = {} |
| 36 | + |
| 37 | + |
| 38 | +class Point(Base): |
| 39 | + x: int |
| 40 | + y: int |
| 41 | + |
| 42 | + def __init__(self, x, y): |
| 43 | + self.x = x |
| 44 | + self.y = y |
| 45 | + |
| 46 | + def move_by(self, dx, dy): |
| 47 | + self.x += dx |
| 48 | + self.y += dy |
| 49 | + |
| 50 | + def __str__(self): |
| 51 | + return f'A Point at {self.x}, {self.y}' |
| 52 | + |
| 53 | + def __repr__(self): |
| 54 | + return f'{self.__class__.__name__}({self.x}, {self.y})' |
| 55 | + |
| 56 | + |
| 57 | +class Circle(Base): |
| 58 | + center: Point |
| 59 | + radius: int |
| 60 | + |
| 61 | + def __init__(self, center, radius): |
| 62 | + self.center = center |
| 63 | + self.radius = radius |
| 64 | + |
| 65 | + @property |
| 66 | + def area(self): |
| 67 | + return pi * self.radius ** 2 |
| 68 | + |
| 69 | + def __str__(self): |
| 70 | + return f'A Circle at {self.center.x}, {self.center.y} and ' + \ |
| 71 | + f'radius {self.radius}' |
| 72 | + |
| 73 | + def __repr__(self): |
| 74 | + return f'{self.__class__.__name__}({self.center!r}, {self.radius!r})' |
0 commit comments