blob: ca75ecc7933843985781df803c1a15039e27df48 [file] [log] [blame]
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001/*
Wenzel Jakobdb028d62015-10-13 23:44:25 +02002 example/example9.cpp -- nested modules, importing modules, and
3 internal references
Wenzel Jakob38bd7112015-07-05 20:05:44 +02004
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +02005 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakob38bd7112015-07-05 20:05:44 +02006
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 "example.h"
12
13void submodule_func() {
14 std::cout << "submodule_func()" << std::endl;
15}
16
17class A {
18public:
19 A(int v) : v(v) { std::cout << "A constructor" << std::endl; }
20 ~A() { std::cout << "A destructor" << std::endl; }
21 A(const A&) { std::cout << "A copy constructor" << std::endl; }
22 std::string toString() { return "A[" + std::to_string(v) + "]"; }
23private:
24 int v;
25};
26
27class B {
28public:
29 B() { std::cout << "B constructor" << std::endl; }
30 ~B() { std::cout << "B destructor" << std::endl; }
31 B(const B&) { std::cout << "B copy constructor" << std::endl; }
32 A &get_a1() { return a1; }
33 A &get_a2() { return a2; }
34
35 A a1{1};
36 A a2{2};
37};
38
39void init_ex9(py::module &m) {
40 py::module m_sub = m.def_submodule("submodule");
41 m_sub.def("submodule_func", &submodule_func);
42
43 py::class_<A>(m_sub, "A")
44 .def(py::init<int>())
45 .def("__repr__", &A::toString);
46
47 py::class_<B>(m_sub, "B")
48 .def(py::init<>())
49 .def("get_a1", &B::get_a1, "Return the internal A 1", py::return_value_policy::reference_internal)
50 .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal)
51 .def_readwrite("a1", &B::a1) // def_readonly uses an internal reference return policy by default
52 .def_readwrite("a2", &B::a2);
Wenzel Jakobdb028d62015-10-13 23:44:25 +020053
54 m.attr("OD") = py::module::import("collections").attr("OrderedDict");
Wenzel Jakob38bd7112015-07-05 20:05:44 +020055}