Home  >  Article  >  Backend Development  >  Python calls object properties or methods through strings

Python calls object properties or methods through strings

不言
不言Original
2018-04-21 14:31:202854browse

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'

Related recommendations:


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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn