Boost Python-全局和本地字典 [英] Boost Python - Global and Local dictionary
问题描述
我正在使用BoostPython在我的C ++项目中嵌入Python,但是我不了解有关Python的所有知识,尤其是名称空间系统.
I'm using BoostPython for embedding Python in my C++ project but I don't understand all stuffs about Python, especially the namespace system.
实际上,我使用了以下代码:
Actually, I used this code:
byte_code = Py_CompileString(filedata, filename, Py_file_input);
// [...]
PyObject* res = NULL;
PyObject* main_module = PyImport_AddModule("__main__");
PyObject* global_dict = PyModule_GetDict(main_module);
PyObject* local_dict = PyDict_New();
py::object local_namespace(py::handle<>(py::borrowed(local_dict)));
// Set a user object (only for this execution)
local_namespace["user_object"] = py::ptr(&MyObject);
res = PyEval_EvalCode( byte_code, global_dict, local_dict );
Py_XDECREF(res);
Py_XDECREF(local_dict);
但是当我执行类似python脚本的时候:
But When I execute a python script like:
def testB():
print("B")
def testA():
testB() # NameError: global name 'testB' is not defined
testA() # Works
testB() # Works
好的,我可以用
res = PyEval_EvalCode( byte_code, global_dict, global_dict );
代替
res = PyEval_EvalCode( byte_code, global_dict, local_dict );
但是我想从任何新的函数定义中保留global_dict(因为当我启动一个新脚本时,我不希望可以从非常旧的执行中调用以前的函数定义!)
But I want preserve the global_dict from any new function definition (Because when I will launch a new script, I don't want that previous function definition from a very old execution can be called !)
这是有关名称空间的问题,不是吗?
This is a problem about namespace, isn't it ?
推荐答案
是的,这是一个名称空间问题.您应该研究Python处理范围的方式(特别是"self"关键字).
Yes, this is a namespace problem. You should look into the way Python handles scope (specifically the "self" keyword).
简而言之,类成员变量和函数的前缀为"self".为了指定它们是当前对象范围的成员."Self"与C ++和C#中的"this"关键字大致相似.
In short, class member variables and functions are prefixed with "self." in order to specify that they are a member of the current object's scope. "Self" is loosely similar to the "this" keyword in C++ and C#.
这篇关于Boost Python-全局和本地字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!