1 class Attr(object):
 2 
 3     def __init__(self, name, type_):
 4         self.name = name
 5         self.type_ = type_
 6 
 7     def __get__(self, instance, cls):
 8         return instance.__dict__[self.name]
 9 
10     def __set__(self, instance, value):
11         if not isinstance(value, self.type_):
12             raise TypeError('expected an %s'% self.type_)
13 
14         instance.__dict__[self.name] = value
15 
16     def __delete__(self, instance):
17         del instance.__dict__[self.name]
18 
19 
20 
21 class Person(object):
22     name = Attr('name', str)
23     age = Attr('age', int)
24     height = Attr('height', float)
25 
26 
27 
28 p = Person()
29 p.name = 'ray'
30 print(p.name)

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-15
  • 2021-10-27
  • 2021-09-15
  • 2021-07-23
猜你喜欢
  • 2021-08-28
  • 2022-12-23
  • 2021-12-14
  • 2022-12-23
  • 2021-12-10
  • 2021-10-22
  • 2021-12-27
相关资源
相似解决方案