如果对象具有给定的命名属性,则hasattr()方法返回true,否则返回false。
hasattr()方法的语法为:
hasattr(object, name)
hasattr()由getattr()调用,以检查是否引发AttributeError。
hasattr()参数
hasattr()方法采用两个参数:
object -要检查其命名属性的对象
name -要搜索的属性的名称
hasattr()返回值
hasattr()方法返回:
True,如果object有给定的被定义的属性
False,如果对象没有给定的被定义的属性
示例:hasattr()如何在Python中工作?
class Person:
age = 23
name = 'Adam'
person = Person()
print('Person有age属性?:', hasattr(person, 'age'))
print('Person 有salary属性?:', hasattr(person, 'salary'))
运行该程序时,输出为:
Person有age属性?: True
Person 有salary属性?: False
Python compile() Python bytes()
展开全部