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

Python calls object properties or methods through strings

不言
Release: 2018-04-21 14:31:20
Original
2889 people have browsed it

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)
  ...:
Copy after login

In [635]: getmethod('upper')
Out[635]: 'JUST FOR TEST'
Copy after login

2. getattr

In [650]: def getmethod2(x, char='just for test'):
  ...:  return getattr(char, x)()
  ...:
Copy after login

In [651]: getmethod2('upper')
Out[651]: 'JUST FOR TEST'
Copy after login

3. Use the built-in library operator

In [648]: def getmethod3(x, char='just for test'):
  ...:  return operator.methodcaller(x, char)(str)
  ...:
Copy after login

In [649]: getmethod3('upper')
Out[649]: 'JUST FOR TEST'
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template