首页 > 编程语言 > 详细

python hasattr()方法和getattr()方法

时间:2020-01-16 14:33:36      阅读:66      评论:0      收藏:0      [点我收藏+]

hasattr() 函数用于判断对象是否包含对应的属性。

hasattr 语法:

hasattr(object, name)

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class Coordinate:
    x = 10
    y = -5
    z = 0
 
point1 = Coordinate() 
print(hasattr(point1, x))
print(hasattr(point1, y))
print(hasattr(point1, z))
print(hasattr(point1, no))  # 没有该属性

True
True
True
False

 

getattr() 函数用于返回一个对象属性值。

getattr 语法:

getattr(object, name[, default])

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> getattr(a, bar)        # 获取属性 bar 值
1
>>> getattr(a, bar2)       # 属性 bar2 不存在,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: A object has no attribute bar2
>>> getattr(a, bar2, 3)    # 属性 bar2 不存在,但设置了默认值
3
>>>

python hasattr()方法和getattr()方法

原文:https://www.cnblogs.com/weisunblog/p/12200111.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!