Python 中的 hasattr() 函数有什么作用?

pythonserver side programmingprogramming

Python 中的 hasattr() 方法

如果对象具有给定的命名属性,则 hasattr() 方法返回 true,否则返回 false。

语法

hasattr() 方法的语法是 −

hasattr(object, name)

getattr() 调用 hasattr() 来检查是否引发 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)

相关文章


有用资源