zoukankan      html  css  js  c++  java
  • python中通过字符串来调用函数,通过字符串来调用变量,将字符串变成变量名

    强调:eval()函数功能虽然强大,但是也很危险,这个方法需要慎重使用。

    利用python中的内置函数 eval() ,函数说明:

    复制代码
    def eval(*args, **kwargs): # real signature unknown
        """
        Evaluate the given source in the context of globals and locals.
        
        The source may be a string representing a Python expression
        or a code object as returned by compile().
        The globals must be a dictionary and locals can be any mapping,
        defaulting to the current globals and locals.
        If only globals is given, locals defaults to it.
        """
        pass
    复制代码

    样例1:

    复制代码
    def function2(name, age):
        print("name: %s, age: %s" % (name, age))
    
    
    if __name__ == '__main__':
        eval("function2")("Alice", 11)
    
        # 或者:
        args = ["Alice", 11]
        kwargs = {}
        eval("function2")(*args, **kwargs)
    
        """
        输出结果都是:
        name: Alice, age: 11
        """
    复制代码

    样例2:

    复制代码
    class Test(object):
        states = [u"大于等于零", u"大于等于二"]
        state2function = {u"大于等于零": "check_gt0", u"大于等于二": "check_gt2"}
    
        @staticmethod
        def check_gt0(x):
            return x >= 0
    
        @staticmethod
        def check_gt2(x):
            return x >= 2
    
        def predict(self, x):
            for state in Test.states:
                check_ans = eval("Test." + Test.state2function[state])(x)  # 调用Test类中的方法
                print(state, Test.state2function[state], x, check_ans)
    
    
    if __name__ == '__main__':
        test = Test()
        test.predict(x=-1)
        test.predict(x=1)
        test.predict(x=2)
    
        """
        输出:
        大于等于零 check_gt0 -1 False
        大于等于二 check_gt2 -1 False
        大于等于零 check_gt0 1 True
        大于等于二 check_gt2 1 False
        大于等于零 check_gt0 2 True
        大于等于二 check_gt2 2 True
        """
    复制代码

    由字符串函数名得到对应的函数

    把函数作为参数的用法比较直观:

    复制代码
    def func(a, b):
        return a + b
    
    def test(f, a, b):    
        print f(a, b)
    
    test(func, 3, 5)
    复制代码

    但有些情况下,‘要传递哪个函数’这个问题事先还不确定,例如函数名与某变量有关。可以利用 func = globals().get(func_name)来得到函数:

    复制代码
    def func_year(s):
        print 'func_year:', s
        
    def func_month(s):
        print 'func_month:', s  
    
    strs = ['year', 'month']
    for s in strs:
        globals().get('func_%s' % s)(s)
    """
    输出:
    func_year: year
    func_month: month
    """
    复制代码

     将字符串变成变量名:

    https://www.cnblogs.com/kaerxifa/p/11424796.html

    参考文章:https://www.cnblogs.com/bymo/p/7327732.html

  • 相关阅读:
    DRF之url注册器组件
    序列化组件的使用及接口设计和优化
    Django 内置字段
    Django 的 ModelForm组件
    Django组件 中间件
    csrf
    django使用redis做缓存
    微信消息推送
    自定制serilazry字段
    小知识,大智慧(restframework 拾忆)
  • 原文地址:https://www.cnblogs.com/mlgjb/p/10683930.html
Copyright © 2011-2022 走看看