您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/2/17 17:56:19发布21次查看
下面为大家分享一篇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 通过字符串调用对象属性或方法的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product