1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| class Person: def __init__(self, name:str, age:int): self.name = name self.age = age ==================================================================================================
class Typed: def __init__(self, type): self.type = type
def __get__(self, instance, owner): pass
def __set__(self, instance, value): print('T.set', self, instance, value) if not isinstance(value, self.type): raise ValueError(value)
class Person: name = Typed(str) age = Typed(int)
def __init__(self, name:str, age:int): self.name = name self.age = age
p1 = Person('tom', 90)
输出: T.set <__main__.Typed object at 0x7f9dd7aaea90> <__main__.Person object at 0x7f9dd7ac8970> tom T.set <__main__.Typed object at 0x7f9dd7adaf40> <__main__.Person object at 0x7f9dd7ac8970> 90
==================================================================================================
import inspect
class Typed: def __init__(self, type): self.type = type
def __get__(self, instance, owner): pass
def __set__(self, instance, value): print('T.set', self, instance, value) if not isinstance(value, self.type): raise ValueError(value)
class TypeAssert: def __init__(self, cls): self.cls = cls
def __call__(self, name, age): params = inspect.signature(self.cls).parameters print(params) for name, param in params.items(): print(name, param.annotation) if param.annotation != param.empty: setattr(self.cls, name, Typed(param.annotation))
@TypeAssert class Person: def __init__(self, name:str, age:int): self.name = name self.age = age
p1 = Person('tom', 90) 输出: OrderedDict([('name', <Parameter "name: str">), ('age', <Parameter "age: int">)]) name <class 'str'> age <class 'int'>
|