Amazing Python 2: "exec/eval/repr"

本文介绍了 Python 中 exec、eval 和 repr 函数的实际应用。通过示例展示了如何使用 exec 动态创建对象,利用 eval 计算表达式的值,以及借助 repr 获取值对应的字符串形式。此外还探讨了这些函数在数据传输等场景下的高效运用。

1. exec:

      Executing command from string.

class PlayerBase():  
    player_name = None    
    def talk(self):
        print self.player_name, ": It takes five."
                
class Kobe(PlayerBase):
    def __init__(self):
        self.player_name = "Kobe."
        
class TMac(PlayerBase):
    def __init__(self):
        self.player_name = "TMac"

input_name = "TMac"
cmd = "player = " + input_name + "()"
exec(cmd)
player.talk()

Output:

TMac : It takes five.

With "exec", objects of different class types can be created directly from strings without "switch-case"!

(In this way, do we still need to use the design pattern of "Simple Factory"?)

 

2. eval:

       Calculating value from string.

>>> eval( ' 2 * 3 ' )
6
 

3. repr:

      Acquiring string from value.

>>> dict = { "First" : 1, "Second" : 2 }
>>> string = repr(dict)
>>> string
"{'Second': 2, 'First': 1}"
>>> string[17:]
"rst': 1}"

 

4. eval & repr:

    Converting between value and string, which is greatly suitable for transmission of high-level data structs (e.g., a dictionary) over socket!

>>> dict = { "First" : 1, "Second" : 2 }
>>> repr(dict)
"{'Second': 2, 'First': 1}"
>>> eval(repr(dict))
{'Second': 2, 'First': 1}
>>> eval(repr(dict)) == dict
True

 

See more at Chapter 15, 简明 Python 教程 .

当你需要在 C++ 中通过 `boost::python` 执行 Python 代码,并且用户提供了一个字符串作为输入时,你需要判断这个字符串是一个表达式 (expression) 还是一段完整的语句块 (statement),以便选择调用 `boost::python::eval` 或者 `boost::python::exec`。 ### 区分 Expression 和 Statement 1. **Expression**: - 表达式的值可以被计算并返回。 - 它通常会生成一个结果。 - 比如简单的数学运算、函数调用等。 2. **Statement**: - 语句是用来执行某些操作的命令序列,比如变量赋值、循环、条件分支等。 - 不一定有返回值或直接的结果输出。 #### 判断方法: 最简单的方式是尝试解析给定的字符串是否能作为一个合法的Python表达式。如果成功,则说明这是一个表达式;反之则可能是语句或其他内容。 ```cpp #include <boost/python.hpp> namespace py = boost::python; bool is_expression(const std::string& code){ try { // 构建一个空模块并将code当作表达式去评估它是否会抛出异常 py::object main_module = py::import("__main__"); py::dict globals = py::extract<py::dict>(main_module.attr("__dict__")()); // 调用 eval 尝试将传入文本解释成 expression ,若失败则捕获错误 py::object result = py::eval(code, globals); return true; } catch(...) {return false;} } // 根据情况选择合适的 API void execute_code(const std::string &str) { if(is_expression(str)){ // 对于表达式使用 eval 函数 std::cout << "This looks like an expression." << std::endl; boost::python::object expr_result = boost::python::eval(str); std::cout << "Evaluated Result: " << expr_result << std::endl; } else{ // 否则是 statement 使用 exec 函数 std::cout << "This seems to be a series of statements or invalid expression for evaluation." << std::endl; boost::python::exec(boost::python::str(str)); } } ``` 请注意以上代码仅用于演示目的,在实际应用中应当对各种可能的情况进行全面考虑,包括但不限于语法检查以及安全性的保障。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值