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
| class Typed: def __init__(self, name, expected_type): self.name = name self.expected_type = expected_type
def __get__(self, instance, owner): print('get--->', instance, owner) if instance is None: return self return instance.__dict__[self.name]
def __set__(self, instance, value): print('set--->', instance, value) if not isinstance(value, self.expected_type): raise TypeError('Expected %s' % str(self.expected_type)) instance.__dict__[self.name] = value
def __delete__(self, instance): print('delete--->', instance) instance.__dict__.pop(self.name)
def typeassert(**kwargs): def decorate(cls): print('类的装饰器开始运行啦------>', kwargs) for name, expected_type in kwargs.items(): setattr(cls, name, Typed(name, expected_type)) return cls
return decorate
@typeassert( name=str, age=int, salary=float ) class People: def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary
print(People.__dict__) p1 = People('lqz', 18, 3333.3)
''' 类的装饰器开始运行啦------> {'name': <class 'str'>, 'age': <class 'int'>, 'salary': <class 'float'>} {'__module__': '__main__', '__init__': <function People.__init__ at 0x10797a400>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None, 'name': <__main__.Typed object at 0x1080b2a58>, 'age': <__main__.Typed object at 0x1080b2ef0>, 'salary': <__main__.Typed object at 0x1080b2c18>} set---> <__main__.People object at 0x1080b22e8> lqz set---> <__main__.People object at 0x1080b22e8> 18 set---> <__main__.People object at 0x1080b22e8> 3333.3 '''
|