为什么swig在使用__getattribute__时不能正确处理AttributeError ?

Why is swig not handling AttributeError correctly when using __getattribute__?

本文关键字:不能 正确处理 AttributeError getattribute 为什么 swig      更新时间:2023-10-16

我有一个在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似乎正确地处理了异常。所以这只是我的代码不工作