【Python】使用 eval 实现反射

示例1 - 简单示例

cmd交互执行

>>> a='1+1'
>>> a
'1+1'
>>> eval(a)
2

示例2 - 使用实例

def query_sorted_example_table_desc(p_code, attr):
    """
    相同p_code内部,根据attr排序,desc
    """
    if hasattr(Example_table, attr):
        try:
            query_str = 'Example_table.query.filter_by(p_code=p_code).order_by(Example_table.' + attr + '.desc()).all()'
            example_table_result = eval(query_str)
        except Exception as e:
            current_app.logger.error(e)
        return example_table_result
    else:
        raise Exception('In query_sorted_example_table, Example_table has no Attribute:' + str(attr))
发布了552 篇原创文章 · 获赞 201 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/sinat_42483341/article/details/103883198