需要属性_get_、set、_delete_方法,在_set_方法内使用isinstance函数做检查。
class Attr(object):
def __init__(self, name, type_):
self.name = name
self.type_ = type_
def __get__(self, instance, owner):
# print('in__get__', instance, owner)
return instance.__dict__[self.name]
def __set__(self, instance, value):
if not isinstance(value, self.type_):
raise TypeError('expected an %s' % self.type_)
instance.__dict__[self.name] = value
def __delete__(self, instance):
# print('in_delete_')
del instance.__dict__[self.name]
class Person(object):
name = Attr('name', str)
age = Attr('age', int)
height = Attr('height', float)
p = Person()
p.name = 'Bob'
print(p.name)
# a = A()
# a.x = 5
# print(a.x) #通过实例访问
# print(A.x) #通过类访问