Last updated: Apr 10, 2024
Reading time·3 min
To check if an object has a specific method:
getattr()
function to get the attribute of the object.callable()
function to check if the attribute is a method.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') method = getattr(emp1, 'get_name', None) if callable(method): print(method()) # 👉️ bobby hadz
We used the getattr()
function to get the get_name
attribute of the object.
The getattr() function returns the value of the provided attribute of the object.
We used None
as the default value for when the attribute doesn't exist.
The last step is to use the callable()
function to check if the attribute is a
method.
The callable function takes an
object as an argument and returns True
if the object appears callable,
otherwise False
is returned.
Alternatively, you can use the hasattr()
function.
This is a three-step process:
hasattr()
function to check if the attribute exists on the object.callable()
function to check if the attribute is callable.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') if hasattr(emp1, 'get_name') and callable(emp1.get_name): print(emp1.get_name()) # 👉️ bobby hadz
The hasattr function takes the following 2 parameters:
Name | Description |
---|---|
object | The object we want to test for the existence of the attribute |
name | The name of the attribute to check for in the object |
hasattr()
function returns True
if the string is the name of one of the object's attributes, otherwise `False` is returned.We used the boolean AND
operator, so for the if
block to run both conditions have to be met.
The object has to have the specified attribute and the attribute has to be callable.
If you use a try/except statement, you would only be checking if the attribute exists on the object, not if it's callable.
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')
If the get_name
attribute doesn't exist on the object, an AttributeError
is
raised and the except
block runs.
However, the attribute could exist on the object and not be callable, in which
case a TypeError
is raised.
The previous two approaches are more direct and explicit and do a better job at checking if an object has a specific method.
You can learn more about the related topics by checking out the following tutorials: