The following is an example of how Python calls object properties or methods through strings. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together
Sometimes you need to pass in properties or methods as parameters. At this time, you can call object properties or methods with strings 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. Use the built-in library operator
In [648]: def getmethod3(x, char='just for test'): ...: return operator.methodcaller(x, char)(str) ...:
In [649]: getmethod3('upper') Out[649]: 'JUST FOR TEST'
Summary of several ways to connect python strings
How to convert python strings into two-dimensional arrays
The above is the detailed content of Python calls object properties or methods through strings. For more information, please follow other related articles on the PHP Chinese website!