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