Python getattr() function can get an attribution defined in a function or class. In this tutorial, we will introduce how to use it.
getattr() is defined:
getattr(object, name[, default])
Here name is a property of object, it is string. This function is same to object.name
However, if name is not in object, it will return default value.
How to use getattr() in Python?
Here are some examples:
class Test: def __init__(self): self.name = "Test" self.age = 30 def show(self): print(self.name) t = Test() name = getattr(t, 'name') print(name)
In this code, we have created two properties self.name and self.age in class Test, which means object t contains them.
Run this code, you will get this output.
If we get a property that is not created in class Test, how about the result?
sex = getattr(t, 'sex') print(sex)
Here sex is not a property of object t, we also have not give it a default value. Run this code, you will get this result:
AttributeError: 'Test' object has no attribute 'sex'
However, if we apply a default value for sex?
It will ouput the default value.
How about getting a function property?
Look at this code below:
class Test: def __init__(self): self.name = "Test" self.age = 30 def show(self): print(self.name) t = Test() show = getattr(t, 'show') show()
We can use function name to get it and run it.
Run this code, you will see: