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

yipeiwu_com6年前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中Dataframe通过print输出多行时显示省略号的实例

在Python中Dataframe通过print输出多行时显示省略号的实例

笔者使用Python进行数据分析时,通过print输出Dataframe中的数据,当Dataframe行数很多时,中间部分显示省略号,如下图所示: 0 项华祥 1...

Python实现全排列的打印

本文为大家分享了Python实现全排列的打印的代码,供大家参考,具体如下 问题:输入一个数字:3,打印它的全排列组合:123 132 213 231 312 321,并进行统计个数。 下...

利用Python实现在同一网络中的本地文件共享方法

本文利用Python3启动简单的HTTP服务器,以实现在同一网络中共享本地文件。 启动HTTP服务器 打开终端,转入目标文件所在文件夹,键入以下命令: $ cd /Users/zer...

Python入门_浅谈for循环、while循环

Python入门_浅谈for循环、while循环

Python中有两种循环,分别为:for循环和while循环。 1. for循环 for循环可以用来遍历某一对象(遍历:通俗点说,就是把这个循环中的第一个元素到最后一个元素依次访问一次)...

Pytorch 保存模型生成图片方式

三通道数组转成彩色图片 img=np.array(img1) img=img.reshape(3,img1.shape[2],img1.shape[3])...