为什么swig在使用__getattribute__时不能正确处理AttributeError ?
Why is swig not handling AttributeError correctly when using __getattribute__?
我有一个在SWIG中从c++导出到Python的类。一切正常。现在我想定义getattribute来处理对变量和函数的虚拟化访问,这些变量和函数是用c++代码中内置的脚本语言定义的。然而,当我使用%pythoncode定义getattribute函数时,它没有按预期工作。如果我找不到变量或函数,我应该引发一个名为AttributeError的异常。然而,SWIG函数getattr在此阻塞。
%pythoncode %{
def __getattribute__(self, attribute):
raise AttributeError(attribute)
%}
现在,如果我这样做,它是好的:
%pythoncode %{
def __getattribute__(self, attribute):
return object.__getattribute__(self, attribute)
%}
因此,当我引发AttributeError时,生成的SWIG getattr的行为不能正常工作,就像我在没有找到属性时应该做的那样。因此,出于我的目的,我将使用第二个示例,并在例程之前插入我自己的代码,以确定是否存在虚拟函数。如果没有,我将让默认的对象getattribute函数处理它。
有更好的方法来处理这个问题吗?
现在我看看这个,我发现它在常规Python 2.7中也不起作用:
class testmethods(object):
def __init__(self):
self.nofunc1 = None
self.nofunc2 = "nofunc2"
def func1(self):
print "func1"
def func2(self):
print "func2"
def __getattribute__(self, attribute):
print "Attribute:",attribute
raise AttributeError(attribute)
这会引发异常,但不会将责任切换到"getattr"函数。那么一个人该如何处理这种情况呢?
好了,把它删掉。如果对象中存在getattr,则引发异常确实有效。
现在,我想我明白了:
def __getattribute__(self, attribute):
try:
defattrib = object.__getattribute__(self, attribute)
except AttributeError,e:
defattrib = None
if defattrib is not None:
return defattrib
# find attributes in user defined functions
...
# if an attribute cannot be found
raise AttributeError(attribute)
这似乎工作良好。Swig getattr似乎正确地处理了异常。所以这只是我的代码不工作
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么我的for循环不能正确获取argv
- Clang-Format 不能正确分配函数参数
- 为什么相应成员不能正确访问成员函数指针
- 为什么 CSpinButtonCtrl 不能正确处理大于 1000 的数字?
- STD ::在C 中的进步不能正确地行为
- 为什么UINT64_T不能正确显示POW(2,64)-1
- 为什么函数不能正确强制转换指针(从基类到派生类)
- 为什么我的可变参数宏不能正确接受任何参数?
- 为什么 g++ 不能正确链接到指定的 -L 路径?
- 为什么我的 qt centralWidget(一个 QGLWidget)不能正确调整大小?
- 双精度不能正确减去小数
- Doxygen不能正确确定返回类型
- 为什么std::sqrt()在C++中不能正确处理双数据
- C++armadillo不能正确求解条件较差的矩阵
- 为什么无符号字符不能正确显示十六进制值
- 为什么swig在使用__getattribute__时不能正确处理AttributeError ?
- Vector和String的Structs不能正确打印
- 套接字在多线程服务器中不能正确接受
- c++的新功能,scanf不能正确读取/打印输入