从 c++ 捕获 boost::python 包装类的实例属性的创建
我用 boost::python 包装(许多)c++ 类。如果我在从 python 脚本分配属性名称时输错了属性名称,Python 会默默地创建新的实例属性,而这绝不是我缩进的内容。有没有办法捕获此类事件(并引发异常?)?
我在网上看到了一些关于这个主题的帖子,但似乎没有一个给出明确的答案;我试图覆盖 __setattr__ &朋友们,但我没能做对;另外我担心可能的性能影响。
干杯,瓦茨拉夫
I am wrapping (many) c++ classes with boost::python. If I mistype the attribute name when assigning it from a python script, python silently creates new instance attribute, which is never what I indent. Is there a way to catch such events (and raise exception?)?
I've seen a few posts on the web on the topic, but none of them seemd to give a definitive answer; I was trying to override __setattr__
& friends, but I was not able to get it right; plus I was concerned about possible performance impact.
Cheers, Vaclav
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
__setattr__
实际上是正确的方法。如果您担心性能,我认为 python 仍然会在内部进行此调用,因此覆盖该函数不应再花费更多成本。__setattr__
的问题是,如果您试图将实现保留在 C++ 代码中,那么实现起来可能会很棘手。这是一个 python 版本:
这是一种使用元类来完成此操作的方法。这种方法的优点是你只需要定义一次 __setattr__ 函数,然后你就可以使用你的注入器类来定义每个类:
如果你想在 C++ 中做同样的事情,那就有点棘手了:
__setattr__
is in fact the way to go. If you're worried about performance, I think python still does this call internally anyway, so overriding the function should not cost any more. The problem with__setattr__
is that if you're trying to keep your implementation inside your c++ code, it can be tricky to implement.Here's a python version:
Here's a way to do it using metaclasses. The advantage of this method is that you only have to define the
__setattr__
function once, then you can just define each class using your injector class:If you want to do the same in c++, it's a bit trickier: