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


本文摘自php中文网,作者小云云,侵删。

本文主要为大家详细介绍了python如何对实例属性进行类型检查,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能帮助到大家。

案例:

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

p = Person()

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

p.age = 18   # 必须是int

p.height = 1.75   # 必须是float

需求:

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

    赋予不正确类型抛出异常


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

#!/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

相关推荐:

JavaScript类型检查与内部属性[[Class]]

以上就是python实现对实例属性进行类型检查的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python3将Python代码打包成exe文件的方法

Python开发安卓app可行吗

Python中property函数的用法

Python int()怎么用

Python适合后端开发么

Python中正则表达式的详细介绍

介绍Python中slice参数过长的处理方法及实例

使用Python开发简单的小游戏

Python cookbook》怎么样

Python运算符优先级有哪些

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...