美文网首页
python(Class6)

python(Class6)

作者: OldSix1987 | 来源:发表于2016-09-11 10:42 被阅读10次

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


    __get__, __set__, __delete__

    
    # 含有以下方法中的一个的类叫做描述符
    class Attr(object):
        def __init__(self, name, type_):
            self.name = name
            self.type_ = type_
    
        def __get__(self, 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):
            del instance.__dict__[self.name]
    
    
    class Person(object):
        name = Attr('name', str)
        age = Attr('age', int)
        height = Attr('height', float)
    
    p1 = Person()
    p1.name = 'Bob'
    print(p1.name)
    p1.age = 17
    print(p1.age)
    
    

    相关文章

      网友评论

          本文标题:python(Class6)

          本文链接:https://www.haomeiwen.com/subject/jrjuettx.html