【发布时间】:2013-02-07 11:12:07
【问题描述】:
我观察到当一种类型时
help
在 Python repl 中,一个得到
Type help() for interactive help, ...
当一种类型时
help()
一个人被踢进帮助模式。我很确定这是因为 site._Helper 定义了__repr__()(第一个示例)和__call__()(第二个示例)。
我喜欢这种行为(仅提示对象和可调用语法),并且我想对通过 SWIG 导出到 Python 的 C++ 类做同样的事情。这是我尝试做的一个简单示例
helpMimic.h
-----------
class HelpMimic
{
public:
HelpMimic() {};
~HelpMimic() {};
char *__repr__();
void operator()(const char *func=NULL);
};
helpMimic.cxx
-------------
char *HelpMimic::__repr__()
{
return "Online help facilities are not yet implemented.";
}
void HelpMimic::operator()(const char *func)
{
log4cxx::LoggerPtr transcriptPtr = oap::getTranscript();
std::string commentMsg("# Online help facilities are not yet implemented. Cannot look up ");
if (func) {
commentMsg += func;
}
else {
commentMsg += "anything.";
}
LOG4CXX_INFO(transcriptPtr, commentMsg);
}
helpMimic.i
-----------
%module sample
%{
#include <helpMimic.h>
%}
class HelpMimic
{
public:
HelpMimic() {};
~HelpMimic() {};
char *__repr__();
void operator()(const char *func=NULL);
};
当我尝试在我的应用程序中使用这个类时,我似乎无法获得通过 help 看到的行为(下面的输出取自嵌入了 Python 的 C++ 应用程序,其中每个输入线通过PyEval_String()发送):
tam = sample.HelpMimic()
tam # echoes 'tam', nothing else
print tam
# _5010b70200000000_p_HelpMimic
print repr(tam)
# <Swig Object of type 'HelpMimic *' at 0x28230a0>
print tam.__repr__()
# Online help facilities are not yet implemented.
最后一个 print 显示方法 __repr__() 存在,但我无法使用更简单的对象引用或使用 repr(tam) 找到它。我还尝试定义__str()__,希望我误解了哪个会被调用,但仍然没有运气。
我尝试在接口文件中使用%extend 指令将__str__() 或__repr__() 定义插入到 SWIG 接口定义文件中,而不是直接在 C++ 中定义它们,但无济于事。
我错过了什么?
【问题讨论】:
-
刚刚试过你的代码,对我来说很好。我注释掉了 LOG4CXX* 行,因为我没有必要的东西来编译它,但除此之外,我什么也没做。它起作用了......为了记录,我在OSX10.8上使用python2.7。不知道我的设置与您的设置有何不同。看来,无论您缺少什么,它都与代码本身无关
-
谢谢。我希望我能找出导致我看到的输出的不同之处......
-
我同意这绝对是非常奇怪的......
-
如何将repr定义为
const char* __repr__() const? -
你在为此调用 swig 时是否使用
-builtin?