Python hasattr()

时间:2020-02-23 14:42:46  来源:igfitidea点击:

Python hasattr()函数用于测试指定的对象是否具有给定的属性。
该函数返回一个布尔值。

Python hasattr()

Python hasattr()函数语法为:

hasattr(object, name)

"对象"可以是其属性将被检查的任何对象。

"名称"应该是要检查的属性的字符串和名称。

在内部,此函数调用getattr(object,name)并返回True
如果getattr()函数调用抛出了" AttributeError",则返回" False"。
否则,返回True。

Python hasattr()示例

让我们看一个hasattr()函数的示例。

class Employee:
  id = 0
  name = ''

  def __init__(self, i, n):
      self.id = i
      self.name = n

d = Employee(10, 'hyman')

if hasattr(d, 'name'):
  print(getattr(d, 'name'))

输出:hyman

Python hasattr()与

动态确定属性值(例如从用户输入获取属性值)时,可以看到hasattr()函数的好处。
由于动态特性,我们无法对对象中的x执行相同的操作。

让我们看另一个示例,在该示例中,我们将要求用户输入属性值,然后使用hasattr()检查该属性值是否存在,然后进行相应处理。

d = Employee(10, 'hyman')

attr = input('\nPlease enter Employee attribute to get details:\n')

if hasattr(d, attr):
  print(attr, '=', getattr(d, attr))
else:
  print('invalid employee attribute')

输出:

Please enter Employee attribute to get details:
id
id = 10

# next iteration with invalid user input
Please enter Employee attribute to get details:
i
invalid employee attribute