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

来源:互联网 发布:mysql数据库连接 编辑:程序博客网 时间:2024/06/01 09:34

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

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'
阅读全文
1 0
原创粉丝点击