eval() 分类: python基础学习 2013-08-16 18:00 324人阅读 评论(0) 收藏

'''

实例1:


输出string模块不以下划线开头的变量内容

'''

import string


for i in dir(string):

    if not callable (eval("string.%s" % i)) and not i.startswith('_'):

        print "string.%s -->" % i,getattr(string,i) # 或eval('string.%s' % i)


import string

print [('%s --->'% i,getattr(string,i)) for i in dir(string) if (not callable(getattr(string,i))) ]


此处调用常量用做判断

备注:

eval(str [,globals [,locals ]])函数将字符串str当成有效Python表达式来求值,并返回计算结果。

同样地, exec语句将字符串str当成有效Python代码来执行.提供给exec的代码的名称空间和exec语句的名称空间相同.


实例2:

>>> def test(a,b):
...         return a+b
...
>>> def test(a,b):
...         return a+b
...
>>> funcname='test'
>>> argtuple=(1,2)

>>>eval(funcname)(argtuple)

等同于:

def test(a,b):
    return a+b

print eval('test')(1,2)


版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2013-08-16 18:00  前行者2011  阅读(108)  评论(0编辑  收藏  举报