0

我有一个在 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 存在于引发异常的对象中,则确实有效。所以swig行为是不正确的。

4

1 回答 1

0

现在,我想我想通了:

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 似乎可以正确处理异常。所以只是我的代码不起作用。

于 2011-12-29T19:02:09.183 回答