Python getattr method


The getattr() function is used to return an object property value.

The gatattr() function returns the value of the named attribute of the object. name must be a string. If the string is the name of one of the objects variables, the result is the value of that variable.

For instance, getattr(x, 'name') is equivalent to x.name. If the named variable does not exist, defaultis returned if provided, otherwise AttributeError is raised.

The advantage is that when writing a project, the input received is a string, and the getattr function makes it easy to use the methods and properties of the class from the user's perspective.

There are also methods with attr such as hasattr, setattr, etc

Related course: Complete Python Programming Course & Exercises

getattr Syntax.

getattr(object, name[, default])

parameters

  • object -- object.
  • name -- string, object property.
  • default -- the default return value, if not provided, will trigger AttributeError in the absence of a corresponding attribute.

return value

  • Returns the object property value.

getattr example

First, let's look at getattr, as the name suggests, to get the property. It should all be getattr(object, "attribution",None), in general we use getattr(object,name) It is similar to getting the value of object.attribution.

Usage of getattr.

For example.

>>> class test:
...     cal=1
...
>>> getattr(test, "cal")
1
>>> test.cal
1
>>>

The following example shows how getattr is used.

>>> class A:
...     b = 3
...     c = 4
...
>>>
>>> # directly on class
>>> getattr(A,'b')
3
>>> # create object
>>> obj = A()
>>> getattr(obj,'b')
3
>>> getattr(obj,'c')
4
>>>

Another example:

>>> class A(object):
... bar = 1 ...
>>> a = A()
>>> getattr(a, 'bar')
# Get property bar value 1
>>> getattr(a, 'bar2')
# attribute bar2 does not exist, trigger exception Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'A' object has no attribute 'bar2'
>>> getattr(a, 'bar2', 3) # property bar2 does not exist, but default value 3 is set