使用描述符对实例属性做类型检查

需要属性_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)    #通过类访问
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值