您好,欢迎访问一九零五行业门户网

python 通过字符串调用对象属性或方法

下面为大家分享一篇python 通过字符串调用对象属性或方法的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧
有时候需要将属性或方法作为参数传入,这个时候可以通过以下几种方式用字符串调用对象属性或方法
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、利用内置库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'
相关推荐:
python字符串连接的几种方式总结
python字符串如何转为二维数组
以上就是python 通过字符串调用对象属性或方法的详细内容。
其它类似信息

推荐信息