Using the getattr Function in Python Classes
The getattr function in Python allows you to access an attribute of a class (or object) or execute a method from outside the class itself.
getattr(class, attribute [, default])
This function requires two mandatory arguments:
- The name of the class
- The name of the attribute as a string (or a variable containing the attribute's name)
Note: The optional third argument, default, returns a specified value if the attribute does not exist in the class. This is very useful as it prevents an error from being raised if the attribute is not found.
Here are some practical examples:
How to Access a Class Attribute
Example 1
Let's create a class object called Persone().
The class contains an attribute (name) and a method (say).
- class Persone():
- name = 'Andrea'
- def say(self, what):
- print(self.name, what)
- print(getattr(Persone, 'name'))
In line 5, which is outside the Persone() class, we access the value of the 'name' attribute and print it to the screen.
The output is:
Andrea
Even though we are outside the class, we can access the information using the getattr() function.
Example 2
Alternatively, we can achieve the same result by assigning the object to a variable in the script.
- class Persone():
- name = 'Andrea'
- def say(self, what):
- print(self.name, what)
- var = Persone()
- attribute = 'name'
- print(getattr(var, attribute))
In this case, we assigned the Persone() object to the variable var.
The final output is still the same:
Andrea
What if the attribute doesn’t exist in the class?
In that case, the getattr() function raises an error.
So, you need to be careful.
>>> print(getattr(Persone, 'name'))
Traceback (most recent call last):
File, line 13, in <module>
print(getattr(Persone, 'name2'))
AttributeError: type object 'Persone' has no attribute 'name2'
To avoid this problem, you can simply add the optional third parameter with any constant value (e.g., 0).
>> print(getattr(Persone, 'name2', 0))
If the attribute doesn't exist, the function returns the value of the constant.
0
If you don't want any output from the function, you can pass an empty string as the parameter.
print(getattr(Persone, 'name2', ''))
How to Execute a Class Method
Let's go back to the code from the previous example.
Now, we'll try to execute a method inside the class.
- class Persone():
- name = 'Andrea'
- def say(self, what):
- print(self.name, what)
- var = Persone()
- getattr(var, 'say')('Hello World!')
In line 6, we use the getattr function to execute the 'say' method in the Persone class.
The parameter to be passed is placed within the parentheses to the right.
Note: For this to work, you must assign the object to a variable (var).
The output is:
Hello World!
The function executed the say method from outside the class.
What if the method doesn't exist?
In this case, the Python interpreter will raise an error.
getattr(var, 'saynot')('Hello')
Traceback (most recent call last):
File, line 17, in <module>
getattr(var, 'saynot')('Hello')
AttributeError: 'Persone' object has no attribute 'saynot'
To avoid the error, you can use the getattr function within a conditional structure, after checking if the method exists in the class using the hasattr() function.
if hasattr(var, 'saynot'):
getattr(var, 'saynot')('Hello')
Another alternative is to handle the error as an exception.
And so on.