Python hasattr() Function
The hasattr()
method returns true if an object has the given named attribute and false if it does not.
Syntax
hasattr(object, name)
hasattr() Parameters
Python hasattr()
function parameters:
Parameter | Condition | Description |
---|---|---|
object | Required | Object whose named attribute is to be checked |
name | Required | Name of the attribute you want to check if exists |
hasattr() Return Value
Python hasattr()
function returns:
True
if object has the given named attributeFalse
if object has no given named attribute
Example: simple example with hasattr() function
For example, let's check if some attributes are in the Car class:
class Car:
brand = "Ford"
number = 12345
car = Car()
print("The car class has brand:", hasattr(Car, "brand"))
print("The car class has specs: ", hasattr(Car, "specs"))
output
The car class has brand: True
The car class has specs: False
Note:
- If the attribute is in the class, then the result of
hasattr()
is True. - If the attribute is not in the class, then the result of
hasattr()
is False.