从c ++中捕获boost :: python-wrapped类的实例属性

时间:2011-05-25 06:39:28

标签: c++ boost-python

我用boost :: python包装(许多)c ++类。如果我从python脚本中分配属性名称时输入错误,python将默认创建新的实例属性,这绝不是我缩进的内容。有没有办法捕获这样的事件(并引发异常?)?

我在网上看过几篇关于这个主题的帖子,但似乎都没有给出明确的答案;我试图覆盖__setattr__&朋友,但我无法做到正确;加上我担心可能会对性能造成影响。

干杯,瓦茨拉夫

2 个答案:

答案 0 :(得分:3)

__setattr__实际上是要走的路。如果你担心性能,我认为python仍然会在内部进行此调用,因此覆盖该函数不应再花费更多。 __setattr__的问题在于,如果您尝试将实现保留在c ++代码中,那么实现起来可能会非常棘手。

这是一个python版本:

# MyClassBase defined in C++ library
class MyClass(object):
    def __init__(self):
        self.test1 = 'test1'
        self.__initialized = True
    def __setattr__(self, name, value):
        if not self.__dict__.has_key('_MyClass__initialized') or self.__dict__.has_key(name):
            object.__setattr__(self, name, value)
        else:
            raise AttributeError("Attribute %s does not exist." % name)

def main():
    o = MyClass()
    print o.test1
    o.test1 = 'test1_set'
    print o.test1
    # This will throw
    o.test2 = 'test2_set'

if __name__ == '__main__':
    main()

这是使用元类执行此操作的方法。这种方法的优点是你只需要定义__setattr__函数一次,然后就可以使用你的注入类来定义每个类:

# create an injector metaclass to add functionality to
# our modules, you can reuse BoostPythonMetaclass for
# all boost::python-exported objects
BoostPythonMetaclass = MyClass.__class__
class injector(object):
    class __metaclass__(BoostPythonMetaclass):
        def __init__(self, name, bases, dict):
            for b in bases:
                if type(b) not in (self, type):
                    for k,v in dict.items():
                        setattr(b,k,v)
                    setattr(b, '__initialized', True)
            return type.__init__(self, name, bases, dict)

        def __setattr__(self, name, value):
            if not self.__dict__.has_key('_MyClass__initialized') or self.__dict__.has_key(name):
                object.__setattr__(self, name, value)
            else:
                raise AttributeError("Attribute %s does not exist." % name)

# Use the injector to add our functionality
class MyClass(injector, MyClass):
    pass

如果你想在c ++中做同样的事情,那就有点棘手了:

using namespace boost::python;

static void SetAttr(object self, str name, object value)
{
    dict d = getattr(self, "__dict__");
    if(d.has_key(name)) {
        setattr(self, name, value);
    } else {
        std::stringstream ss;
        ss << "Method" << extract<std::string>(name) << "does not exist.";
        PyErr_SetString(PyExc_AttributeError, ss.str().c_str());
        throw error_already_set();
    }
}

BOOST_PYTHON_MODULE(mymodule)
{
    class_<MyClass>("MyClass")
        .def("__setattr__", &SetAttr);
}

答案 1 :(得分:2)

using namespace boost::python;

static object __setattr__native;           //#Object for saving native boost __setattr__() method
//#Hook-setter for method __setattr__(). Checks attribute exists and call native __setattr__ if its exists
static void SetAttr_only_exists(object self, str name, object value)
{
    getattr(self, name);                   //#Get attribute or exception if attribute not exists
    __setattr__native(self, name, value);  //#Call native __setattr__()
    return;
}
BOOST_PYTHON_MODULE(mymodule)
{
    myClass = class_<MyClass>("MyClass")
       .def("someMethod", &MyClass::someMethod);

    __setattr__native = myClass.attr("__setattr__");   //#Saving boost __setattr__() method
    myClass.def("__setattr__", &SetAttr_only_exists); //#Set __setattr__() hook method

}