python如何对实例属性进行类型检查

yipeiwu_com7年前Python基础

本文实例为大家分享了python对实例属性进行类型检查的具体代码,供大家参考,具体内容如下

案例:

在某项目中,我们实现了一些类,并希望能像静态语言那样对他们的实例属性进行类型检查

              p = Person()

              p.name = ‘xi_xi'          # 必须是str

              p.age = 18                    # 必须是int

              p.height = 1.75               # 必须是float

需求:

    可以对实例变量名指定类型

    赋予不正确类型抛出异常

#!/usr/bin/python3
 
 
class Attr(object):
 """
 对Person类中属性进行类型检查
 """
 # 传入字段名字 + 指定字段类型
 def __init__(self, name, style):
  self.name = name
  self.style = style
  
 # 取值
 def __get__(self, instance, owner):
  return instance.__dict__[self.name]
  
 # 设值
 def __set__(self, instance, value):
  # 判断参数类型是否满足条件
  if isinstance(value, self.style):
   instance.__dict__[self.name] = value
  else:
   raise TypeError('need type: %s' % self.style)
  
 # 删除值
 def __delete__(self, instance):
  del instance.__dict__[self.name]
 
 
class Person(object):
 name = Attr('name', str)
 age = Attr('age', int)
 height = Attr('height', float)
  
 
if __name__ == '__main__':
 p = Person()
  
 p.name = 'xi_xi'
 # p.name = 55
 p.age = 18
 p.height = 1.75
 print(p.name, p.age, p.height)
  
 del p.height

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python搭建代理IP池实现检测IP的方法

Python搭建代理IP池实现检测IP的方法

在获取 IP 时,已经成功将各个网站的代理 IP 获取下来了,然后就需要一个检测模块来对所有的代理进行一轮轮的检测,检测可用就设置为满分,不可用分数就减 1,这样就可以实时改变每个代理的...

django加载本地html的方法

django加载本地html的方法

django加载本地html from django.shortcuts import render from django.http import HttpResponse fro...

解决python彩色螺旋线绘制引发的问题

解决python彩色螺旋线绘制引发的问题

彩色螺旋线的绘制代码如下: import turtle import time turtle.pensize(2) turtle.bgcolor('black') colors =...

浅谈pandas中DataFrame关于显示值省略的解决方法

浅谈pandas中DataFrame关于显示值省略的解决方法

python的pandas库是一个非常好的工具,里面的DataFrame更是常用且好用,最近是越用越觉得设计的漂亮,pandas的很多细节设计的都非常好,有待使用过程中发掘。 好了,发完...

Python 基础教程之str和repr的详解

Python str和repr的详解 str可以将值转化为合理的字符串形式,以便用户可以理解; repr会以合法Python表达式的形式来表达值。 举例如下: # str输出用户...