Recently, in python development, you wanted to implement string access to functions. I searched some methods on the Internet, but found none of them simple enough. Finally, I implemented this functionality using python’s built-in getattr method, which is very simple and shared here.


First, a brief introduction to the getattr method

Introduction to the Python getattr() function

 

describe

The getattr() function returns the value of an object property.

grammar

Getattr grammar:

getattr(object, name[, default])
Copy the code

parameter

  • Object — Object.
  • Name — String, object property.
  • Default — The default return value. If this parameter is not provided, AttributeError is raised when there is no corresponding attribute.

The return value

Returns the value of the object property.

The instance

The following example shows how getattr can be used:

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

 

The implementation of calling a function through a string

 

Create a new Python script named main.py

import main as this

def add(a,b) :
    c = a + b
    return c

if __name__ == "__main__":
    out = getattr(this,"add") (1.2)
    print(out)
Copy the code

Why access a function through a string

In my opinion, strings are much easier to pass than functions, for example through command line arguments or constants that can be easily passed from script to script.