Python hasattr() 函数



Python hasattr() 函数 用于检查对象是否包含指定的属性。如果属性存在,则返回 True,否则返回 False。

在访问属性之前,可以使用此函数确保属性存在,这有助于防止运行时错误。hasattr() 函数Python 中的内置函数之一

要获取和设置 属性,可以使用 getattr()setattr() 函数。

语法

Python hasattr() 函数的语法如下所示:

hasattr(object, attribute)

参数

以下是 python hasattr() 函数的参数:

  • object - 此参数指定需要检查其命名属性的对象。

  • attribute - 此参数表示要在指定对象中搜索的字符串。

返回值

Python hasattr() 函数返回一个布尔值。

hasattr() 函数示例

练习以下示例以了解如何在 Python 中使用 hasattr() 函数

示例:hasattr() 函数的使用

以下是 Python hasattr() 函数的示例。在这里,我们定义了一个类并实例化了其对象,并尝试验证它是否包含指定的属性。

class Car:
   wheels = 4

transport = Car()
output = hasattr(transport, "wheels") 
print("The car has wheels:", output)

执行上述程序后,将生成以下输出:

The car has wheels: True

示例:检查继承类的属性

hasattr() 函数也可以轻松检查继承的属性。在下面的代码中,我们定义了一个父类及其子类。然后,使用 hasattr() 函数,我们检查子类是否能够继承其父类的属性。

class Car:
   wheels = 4

class Tata(Car):
   fuelType = "Petrol"

newCar = Tata()
output = hasattr(newCar, "wheels") 
print("The new car has wheels:", output)

执行上述程序后,将获得以下输出:

The new car has wheels: True

示例:当属性不存在时使用 hasattr() 函数

如果给定对象中不存在指定的属性,则 hasattr() 函数将返回 false。这里,传递的属性不属于任何定义的类。因此,结果将为 False。

class Car:
    wheels = 4

class Tata(Car):
    fuelType = "Petrol"

newCar = Tata()
output = hasattr(newCar, "wings") 
print("The new car has wheels:", output)

执行上述程序后,将获得以下输出:

The new car has wheels: False

示例 4

在以下示例中,我们使用 hasattr() 函数来验证给定的方法是否在指定的类中定义。

class AI:
   def genAI(self):
      pass

chatGpt = AI()
output = hasattr(chatGpt, "genAI")
print("The chat GPT is genAI:", output)

执行上述程序后,将显示以下输出:

The chat GPT is genAI: True
python_built_in_functions.htm
广告
© . All rights reserved.