質問

I have a class that is getting exported from C++ to Python in SWIG. Everything works fine. Now I want to define getattribute to handle virtualize access to variables and functions that are defined in a scripting language built into the C++ code. However when I define the getattribute function using %pythoncode it is not working as expected. If I cannot find the variables or functions I am supposed to raise and exception called AttributeError. However the SWIG function getattr chokes on this.

%pythoncode %{
    def __getattribute__(self, attribute):
        raise AttributeError(attribute)

%}

Now if I do this it is okay:

%pythoncode %{
    def __getattribute__(self, attribute):
        return object.__getattribute__(self, attribute)
%}

So, the behaviour of the SWIG produced getattr does not work properly when I raise an AttributeError like I am supposed to do when and attribute is not found. So, for my purposes I will be using the second example and inserting my own code before the routine to determine if a virtualized function exists. If not I will let the default object getattribute function handle it.

Is there a better way to approach this?

Now that I look at this i am finding it does not work in regular Python 2.7 either:

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)

This raises the exception, but does not switch responsibility to "getattr" function. So how is one supposed to handle this?

Okay, strike that. If getattr is present in the object raising the exception does work. So swig behaviour is not correct.

役に立ちましたか?

解決

Now, I think I figured this out:

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) 

This seems to work fine. swig getattr seems to handle the exception properly. So it is just my code that was not working.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top