hasattr() 函数在 Python 中的作用是什么?
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)广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP