Python 中 hasattr() 函数是什么?

Python 中 hasattr() 函数是什么?

更多Python相关文章,请阅读:Python 教程

Python 的 hasattr() 方法

hasattr() 方法会在对象拥有指定的属性时返回 True,否则返回 False。

语法

hasattr() 方法的语法为 −

hasattr(object, name)

hasattr() 方法被 getattr() 调用,以检查是否需要引发 AttributeError。

hasattr() 方法接受两个参数 −

hasattr() 方法返回 −

当对象拥有指定命名的属性时返回 True

当对象没有指定命名的属性时返回 False

示例

class Male:
    age = 21
    name = 'x'
x = Male()
print('Male has age?:', hasattr(x, 'age'))
print('Male has salary?:', hasattr(x, 'salary'))

输出

这将输出

('Male has age?:', True)
('Male has salary?:', False)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程