脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 通过字符串调用对象属性或方法的实例讲解

python 通过字符串调用对象属性或方法的实例讲解

2021-02-03 00:39晓东邪 Python

下面小编就为大家分享一篇python 通过字符串调用对象属性或方法的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

有时候需要将属性或方法作为参数传入,这个时候可以通过以下几种方式用字符串调用对象属性或方法

1、eval

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

2、getattr

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

3、利用内置库operator

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

以上这篇python 通过字符串调用对象属性或方法的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/xiaodongxiexie/article/details/77197947

延伸 · 阅读

精彩推荐