MCPcopy Create free account
hub / github.com/pybind/pybind11 / TEST_SUBMODULE

Function TEST_SUBMODULE

tests/test_operator_overloading.cpp:150–281  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

148#endif
149
150TEST_SUBMODULE(operators, m) {
151
152 // test_operator_overloading
153 py::class_<Vector2>(m, "Vector2")
154 .def(py::init<float, float>())
155 .def(py::self + py::self)
156 .def(py::self + float())
157 .def(py::self - py::self)
158 .def(py::self - float())
159 .def(py::self * float())
160 .def(py::self / float())
161 .def(py::self * py::self)
162 .def(py::self / py::self)
163 .def(py::self += py::self)
164 .def(py::self -= py::self)
165 .def(py::self *= float())
166 .def(py::self /= float())
167 .def(py::self *= py::self)
168 .def(py::self /= py::self)
169 .def(float() + py::self)
170 .def(float() - py::self)
171 .def(float() * py::self)
172 .def(float() / py::self)
173 .def(-py::self)
174 .def("__str__", &Vector2::toString)
175 .def("__repr__", &Vector2::toString)
176 .def(py::self == py::self)
177 .def(py::self != py::self)
178 .def(py::hash(py::self))
179 // N.B. See warning about usage of `py::detail::abs(py::self)` in
180 // `operators.h`.
181 .def("__abs__", [](const Vector2 &v) { return abs(v); });
182
183 m.attr("Vector") = m.attr("Vector2");
184
185 // test_operators_notimplemented
186 // #393: need to return NotSupported to ensure correct arithmetic operator behavior
187 py::class_<C1>(m, "C1").def(py::init<>()).def(py::self + py::self);
188
189 py::class_<C2>(m, "C2")
190 .def(py::init<>())
191 .def(py::self + py::self)
192 .def("__add__", [](const C2 &c2, const C1 &c1) { return c2 + c1; })
193 .def("__radd__", [](const C2 &c2, const C1 &c1) { return c1 + c2; });
194
195 // test_nested
196 // #328: first member in a class can't be used in operators
197 struct NestABase {
198 int value = -2;
199 };
200 py::class_<NestABase>(m, "NestABase")
201 .def(py::init<>())
202 .def_readwrite("value", &NestABase::value);
203
204 struct NestA : NestABase {
205 int value = 3;
206 NestA &operator+=(int i) {
207 value += i;

Callers

nothing calls this directly

Calls 3

hashFunction · 0.85
absFunction · 0.85
attrMethod · 0.80

Tested by

no test coverage detected