zoukankan      html  css  js  c++  java
  • 使用描述符多实例属性做类型检查

     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)
  • 相关阅读:
    函数的定义
    编码转换
    bytes类型
    用py操作文件(file类的功能)
    HASH哈希
    二进制、bit、 bytes
    POJ3225
    POJ1436
    HDU1394
    HDU1272
  • 原文地址:https://www.cnblogs.com/ray-mmss/p/10487288.html
Copyright © 2011-2022 走看看