SoFunction
Updated on 2024-11-13

Example of python calling an object property or method via a string

Sometimes you need to pass a property or method as a parameter, and you can call an object property or method with a string in the following ways

1、eval

In [634]: def getmethod(x,char='just for test'):
  ...:  return eval('str.%s' % x)(char)
  ...: 
In [635]: getmethod('upper')
Out[635]: 'JUST FOR TEST'

2、getattr

In [650]: def getmethod2(x, char='just for test'):
  ...:  return getattr(char, x)()
  ...: 
In [651]: getmethod2('upper')
Out[651]: 'JUST FOR TEST'

3, the use of built-in library operator

In [648]: def getmethod3(x, char='just for test'):
  ...:  return (x, char)(str)
  ...: 
In [649]: getmethod3('upper')
Out[649]: 'JUST FOR TEST'

The above example of this python calling object properties or methods via strings is all I have to share with you, I hope it will give you a reference, and I hope you will support me more.