gpt4 book ai didi

python - Boost Python重写相等运算符

转载 作者:行者123 更新时间:2023-11-30 02:39:37 25 4
gpt4 key购买 nike

我正在尝试为我通过 boost python 公开的类覆盖 python 相等运算符。

所以我的代码看起来像这样:

   class_<MyClass, boost::noncopyable, boost::shared_ptr<MyClass> >("MyClass", no_init)
.def("foo", &MyClass::foo)
.
.
.
.def("__eq__", &MyClass::operator==)
.def("__ne__", &MyClass::operator!=)

然而在 python 中,当我获取表示相同 C++ 对象的对象的 2 个实例,但是来自不同的 python 对象时,它们永远不相等...

因此:

from myPackage import myClass

v1 = myClass.get("abc")
v2 = myClass.get("abc")
if v1 == v2:
print "true"
else:
print "false"

总是打印错误。 (为了简单起见,我省略了对象的 get 函数定义)

有什么想法吗?

最佳答案

考虑为 MyClass::operator==() 编写一个 C++ 测试用例来验证其实现。公开运算符的 Boost.Python 代码是正确的。


这是一个例子 demonstrating将 C++ 类的比较运算符公开为相等和不等丰富比较方法:

#include <iostream>
#include <string>
#include <boost/make_shared.hpp>
#include <boost/python.hpp>
#include <boost/shared_ptr.hpp>

class foo
{
public:
foo(const char* value) : value_(value) {}
foo(const foo&) = delete;
foo& operator=(const foo&) = delete;

bool operator==(const foo& rhs)
{
std::cout << "foo::operator==()" << std::endl;
return value_ == rhs.value_;
}

bool operator!=(const foo& rhs)
{
std::cout << "foo::operator!=()" << std::endl;
return !(*this == rhs);
}

std::string get_value() const { return value_; }
void set_value(std::string value) { value_ = value; }

private:
std::string value_;
};

boost::shared_ptr<foo> make_foo(const char* value)
{
return boost::make_shared<foo>(value);
}

BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<foo, boost::shared_ptr<foo>, boost::noncopyable>(
"Foo", python::no_init)
.def("__init__", python::make_constructor(&make_foo))
.def("__eq__", &foo::operator==)
.def("__ne__", &foo::operator!=)
.add_property("value", &foo::get_value, &foo::set_value)
;
}

交互使用:

>>> import example
>>> foo1 = example.Foo("abc")
>>> foo2 = example.Foo("abc")
>>> foo3 = example.Foo("def")
>>> assert(foo1 == foo1)
foo::operator==()
>>> assert(foo1 == foo2)
foo::operator==()
>>> assert(foo1 is not foo2)
>>> assert(foo1 != foo3)
foo::operator!=()
foo::operator==()
>>> foo1.value = foo3.value
>>> assert(foo1 != foo2)
foo::operator!=()
foo::operator==()
>>> assert(foo1 == foo3)
foo::operator==()

如以上输出所示,C++ 比较运算符是从 Python 调用的。


在示例中,make_foo() 工厂函数创建了唯一的 C++ foo 实例。因此,我选择将工厂方法的实现细节隐藏到 Python,方法是将 make_foo() 包装为构造函数并将其公开为 __init__ 方法。作为demonstrated here , 如果对象创建是通过静态方法发生的,仍然可以检查相等性。另一方面,如果像 get() 这样的静态工厂方法可以返回现有 foo 实例的句柄,那么人们可能会期望相等性和身份比较都适用于 Foo Python 对象(即 assert(Foo.get("abc") is Foo.get("abc"))。要返回对同一 Python 对象的引用,可以需要管理关联的 PyObject

关于python - Boost Python重写相等运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29619799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com