test_modules.cpp revision 11986
1/* 2 tests/test_modules.cpp -- nested modules, importing modules, and 3 internal references 4 5 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 6 7 All rights reserved. Use of this source code is governed by a 8 BSD-style license that can be found in the LICENSE file. 9*/ 10 11#include "pybind11_tests.h" 12#include "constructor_stats.h" 13 14std::string submodule_func() { 15 return "submodule_func()"; 16} 17 18class A { 19public: 20 A(int v) : v(v) { print_created(this, v); } 21 ~A() { print_destroyed(this); } 22 A(const A&) { print_copy_created(this); } 23 A& operator=(const A ©) { print_copy_assigned(this); v = copy.v; return *this; } 24 std::string toString() { return "A[" + std::to_string(v) + "]"; } 25private: 26 int v; 27}; 28 29class B { 30public: 31 B() { print_default_created(this); } 32 ~B() { print_destroyed(this); } 33 B(const B&) { print_copy_created(this); } 34 B& operator=(const B ©) { print_copy_assigned(this); a1 = copy.a1; a2 = copy.a2; return *this; } 35 A &get_a1() { return a1; } 36 A &get_a2() { return a2; } 37 38 A a1{1}; 39 A a2{2}; 40}; 41 42test_initializer modules([](py::module &m) { 43 py::module m_sub = m.def_submodule("submodule"); 44 m_sub.def("submodule_func", &submodule_func); 45 46 py::class_<A>(m_sub, "A") 47 .def(py::init<int>()) 48 .def("__repr__", &A::toString); 49 50 py::class_<B>(m_sub, "B") 51 .def(py::init<>()) 52 .def("get_a1", &B::get_a1, "Return the internal A 1", py::return_value_policy::reference_internal) 53 .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal) 54 .def_readwrite("a1", &B::a1) // def_readonly uses an internal reference return policy by default 55 .def_readwrite("a2", &B::a2); 56 57 m.attr("OD") = py::module::import("collections").attr("OrderedDict"); 58}); 59