Python 中检查对象是否具有特定方法

Python 中要检查对象是否具有特定方法:

  1. 使用 getattr() 函数获取对象的属性。
  2. 使用 callable() 函数检查属性是否为方法。
  3. 如果满足条件,则对象具有指定的方法。
class Employee():
    def __init__(self, first, last):
        self.first = first
        self.last = last

    def get_name(self):
        return f'{self.first} {self.last}'


emp1 = Employee('fql', 'zadmei')

method = getattr(emp1, 'get_name', None)


if callable(method):
    print(method())  # ?️ fql zadmei

我们使用 getattr() 函数来获取对象的 get_name 属性。

getattr 函数返回对象提供的属性的值。

该函数将对象、属性名称和对象上不存在该属性时的默认值作为参数。

当属性不存在时,我们使用 None 作为默认值。

最后一步是使用 callable() 函数来检查属性是否是方法。

可调用函数将一个对象作为参数,如果该对象看起来可调用,则返回 True,否则返回 False。

如果指定的属性存在于对象上并且该属性是可调用的,我们可以安全地假设它是一个方法。

或者,我们可以使用 hasattr() 函数。

使用 hasattr() 检查对象是否具有特定方法

要检查对象是否具有特定方法:

  1. 使用 hasattr() 函数检查对象上是否存在该属性。
  2. 使用 callable() 函数检查属性是否可调用。
  3. 如果满足这两个条件,则该对象具有指定的方法。
class Employee():
    def __init__(self, first, last):
        self.first = first
        self.last = last

    def get_name(self):
        return f'{self.first} {self.last}'


emp1 = Employee('fql', 'zadmei')

if hasattr(emp1, 'get_name') and callable(emp1.get_name):
    print(emp1.get_name())  # ?️ fql zadmei

hasattr 函数采用以下 2 个参数:

  • object 我们要测试属性是否存在的对象
  • name 要在对象中检查的属性的名称

如果字符串是对象属性之一的名称,则 hasattr() 函数返回 True,否则返回“False”。

我们使用了布尔运算符和运算符,因此要运行 if 块,必须满足两个条件。

该对象必须具有指定的属性,并且该属性必须是可调用的。

如果你使用 try/except 语句,你只会检查对象上是否存在该属性,而不是它是否可调用。

class Employee():
    def __init__(self, first, last):
        self.first = first
        self.last = last

    def get_name(self):
        return f'{self.first} {self.last}'


emp1 = Employee('bobby', 'hadz')

try:
    result = emp1.get_name()
except AttributeError:
    print('The attribute does NOT exist')

如果对象上不存在 get_name 属性,则会引发 AttributeError 并运行 except 块。

但是 ,该属性可能存在于对象上并且不可调用,在这种情况下会引发 TypeError

前两种方法更直接和明确,并且在检查对象是否具有特定方法方面做得更好。