Python hasattr() 函数检查对象是否包含指定的属性。如果存在属性,则返回 True,否则返回 False。
如果要在访问属性之前确保属性存在,可以使用此函数,这有助于防止运行时错误。hasattr() 函数是 Python 中的内置函数之一。
要获取和设置属性,您可以分别使用 getattr() 和 setattr() 函数。
语法
Python hasattr() 函数的语法如下 -
hasattr(object, attribute)
参数
以下是 python hasattr() 函数的参数 -
- object − 此参数指定需要检查其 named 属性的对象。
- 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
示例:当 attribute 不存在时使用 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