blob: cfe349fda7347e6e24b9e3ca4a1540161cd5cc74 [file] [log] [blame]
Wenzel Jakob28f98aa2015-10-13 02:57:16 +02001.. _classes:
2
3Object-oriented code
4####################
5
6Creating bindings for a custom type
7===================================
8
9Let's now look at a more complex example where we'll create bindings for a
10custom C++ data structure named ``Pet``. Its definition is given below:
11
12.. code-block:: cpp
13
14 struct Pet {
15 Pet(const std::string &name) : name(name) { }
16 void setName(const std::string &name_) { name = name_; }
17 const std::string &getName() const { return name; }
18
19 std::string name;
20 };
21
22The binding code for ``Pet`` looks as follows:
23
24.. code-block:: cpp
25
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020026 #include <pybind11/pybind11.h>
Wenzel Jakob93296692015-10-13 23:21:54 +020027
Wenzel Jakob10e62e12015-10-15 22:46:07 +020028 namespace py = pybind11;
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020029
Wenzel Jakobb1b71402015-10-18 16:48:30 +020030 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020031 py::module m("example", "pybind11 example plugin");
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020032
33 py::class_<Pet>(m, "Pet")
34 .def(py::init<const std::string &>())
35 .def("setName", &Pet::setName)
36 .def("getName", &Pet::getName);
37
38 return m.ptr();
39 }
40
41:class:`class_` creates bindings for a C++ `class` or `struct`-style data
42structure. :func:`init` is a convenience function that takes the types of a
43constructor's parameters as template arguments and wraps the corresponding
44constructor (see the :ref:`custom_constructors` section for details). An
45interactive Python session demonstrating this example is shown below:
46
47.. code-block:: python
48
49 % python
50 >>> import example
51 >>> p = example.Pet('Molly')
52 >>> print(p)
53 <example.Pet object at 0x10cd98060>
54 >>> p.getName()
55 u'Molly'
56 >>> p.setName('Charly')
57 >>> p.getName()
58 u'Charly'
59
60Keyword and default arguments
61=============================
62It is possible to specify keyword and default arguments using the syntax
63discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
64and :ref:`default_args` for details.
65
66Binding lambda functions
67========================
68
69Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
70
71.. code-block:: python
72
73 >>> print(p)
74 <example.Pet object at 0x10cd98060>
75
76To address this, we could bind an utility function that returns a human-readable
77summary to the special method slot named ``__repr__``. Unfortunately, there is no
78suitable functionality in the ``Pet`` data structure, and it would be nice if
79we did not have to change it. This can easily be accomplished by binding a
80Lambda function instead:
81
82.. code-block:: cpp
83
84 py::class_<Pet>(m, "Pet")
85 .def(py::init<const std::string &>())
86 .def("setName", &Pet::setName)
87 .def("getName", &Pet::getName)
88 .def("__repr__",
89 [](const Pet &a) {
90 return "<example.Pet named '" + a.name + "'>";
91 }
92 );
93
94Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
95With the above change, the same Python code now produces the following output:
96
97.. code-block:: python
98
99 >>> print(p)
100 <example.Pet named 'Molly'>
101
102Instance and static fields
103==========================
104
105We can also directly expose the ``name`` field using the
106:func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
107method also exists for ``const`` fields.
108
109.. code-block:: cpp
110
111 py::class_<Pet>(m, "Pet")
112 .def(py::init<const std::string &>())
113 .def_readwrite("name", &Pet::name)
114 // ... remainder ...
115
116This makes it possible to write
117
118.. code-block:: python
119
120 >>> p = example.Pet('Molly')
121 >>> p.name
122 u'Molly'
123 >>> p.name = 'Charly'
124 >>> p.name
125 u'Charly'
126
127Now suppose that ``Pet::name`` was a private internal variable
128that can only be accessed via setters and getters.
129
130.. code-block:: cpp
131
132 class Pet {
133 public:
134 Pet(const std::string &name) : name(name) { }
135 void setName(const std::string &name_) { name = name_; }
136 const std::string &getName() const { return name; }
137 private:
138 std::string name;
139 };
140
141In this case, the method :func:`class_::def_property`
142(:func:`class_::def_property_readonly` for read-only data) can be used to
Wenzel Jakob93296692015-10-13 23:21:54 +0200143provide a field-like interface within Python that will transparently call
144the setter and getter functions:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200145
146.. code-block:: cpp
147
148 py::class_<Pet>(m, "Pet")
149 .def(py::init<const std::string &>())
150 .def_property("name", &Pet::getName, &Pet::setName)
151 // ... remainder ...
152
153.. seealso::
154
155 Similar functions :func:`class_::def_readwrite_static`,
156 :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
157 and :func:`class_::def_property_readonly_static` are provided for binding
158 static variables and properties.
159
Wenzel Jakob2dfbade2016-01-17 22:36:37 +0100160.. _inheritance:
161
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200162Inheritance
163===========
164
165Suppose now that the example consists of two data structures with an
166inheritance relationship:
167
168.. code-block:: cpp
169
170 struct Pet {
171 Pet(const std::string &name) : name(name) { }
172 std::string name;
173 };
174
175 struct Dog : Pet {
176 Dog(const std::string &name) : Pet(name) { }
177 std::string bark() const { return "woof!"; }
178 };
179
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100180There are two different ways of indicating a hierarchical relationship to
181pybind11: the first is by specifying the C++ base class explicitly during
182construction using the ``base`` attribute:
183
184.. code-block:: cpp
185
186 py::class_<Pet>(m, "Pet")
187 .def(py::init<const std::string &>())
188 .def_readwrite("name", &Pet::name);
189
190 py::class_<Dog>(m, "Dog", py::base<Pet>() /* <- specify C++ parent type */)
191 .def(py::init<const std::string &>())
192 .def("bark", &Dog::bark);
193
194Alternatively, we can also assign a name to the previously bound ``Pet``
195:class:`class_` object and reference it when binding the ``Dog`` class:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200196
197.. code-block:: cpp
198
199 py::class_<Pet> pet(m, "Pet");
200 pet.def(py::init<const std::string &>())
201 .def_readwrite("name", &Pet::name);
202
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100203 py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200204 .def(py::init<const std::string &>())
205 .def("bark", &Dog::bark);
206
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100207Functionality-wise, both approaches are completely equivalent. Afterwards,
208instances will expose fields and methods of both types:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200209
Wenzel Jakob93296692015-10-13 23:21:54 +0200210.. code-block:: python
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200211
212 >>> p = example.Dog('Molly')
213 >>> p.name
214 u'Molly'
215 >>> p.bark()
216 u'woof!'
217
218Overloaded methods
219==================
220
221Sometimes there are several overloaded C++ methods with the same name taking
222different kinds of input arguments:
223
224.. code-block:: cpp
225
226 struct Pet {
227 Pet(const std::string &name, int age) : name(name), age(age) { }
228
229 void set(int age) { age = age; }
230 void set(const std::string &name) { name = name; }
231
232 std::string name;
233 int age;
234 };
235
236Attempting to bind ``Pet::set`` will cause an error since the compiler does not
237know which method the user intended to select. We can disambiguate by casting
238them to function pointers. Binding multiple functions to the same Python name
Wenzel Jakob0fb85282015-10-19 23:50:51 +0200239automatically creates a chain of function overloads that will be tried in
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200240sequence.
241
242.. code-block:: cpp
243
244 py::class_<Pet>(m, "Pet")
245 .def(py::init<const std::string &, int>())
246 .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
247 .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
248
249The overload signatures are also visible in the method's docstring:
250
251.. code-block:: python
252
253 >>> help(example.Pet)
254
255 class Pet(__builtin__.object)
256 | Methods defined here:
257 |
258 | __init__(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100259 | Signature : (Pet, str, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200260 |
261 | set(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100262 | 1. Signature : (Pet, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200263 |
264 | Set the pet's age
265 |
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100266 | 2. Signature : (Pet, str) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200267 |
268 | Set the pet's name
Wenzel Jakob93296692015-10-13 23:21:54 +0200269
270.. note::
271
272 To define multiple overloaded constructors, simply declare one after the
273 other using the ``.def(py::init<...>())`` syntax. The existing machinery
274 for specifying keyword and default arguments also works.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200275
276Enumerations and internal types
277===============================
278
Wenzel Jakob93296692015-10-13 23:21:54 +0200279Let's now suppose that the example class contains an internal enumeration type,
280e.g.:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200281
282.. code-block:: cpp
283
284 struct Pet {
285 enum Kind {
286 Dog = 0,
287 Cat
288 };
289
290 Pet(const std::string &name, Kind type) : name(name), type(type) { }
291
292 std::string name;
293 Kind type;
294 };
295
296The binding code for this example looks as follows:
297
298.. code-block:: cpp
299
300 py::class_<Pet> pet(m, "Pet");
301
302 pet.def(py::init<const std::string &, Pet::Kind>())
303 .def_readwrite("name", &Pet::name)
304 .def_readwrite("type", &Pet::type);
305
306 py::enum_<Pet::Kind>(pet, "Kind")
307 .value("Dog", Pet::Kind::Dog)
308 .value("Cat", Pet::Kind::Cat)
309 .export_values();
310
311To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
312``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
Wenzel Jakob93296692015-10-13 23:21:54 +0200313constructor. The :func:`enum_::export_values` function exports the enum entries
314into the parent scope, which should be skipped for newer C++11-style strongly
315typed enums.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200316
317.. code-block:: python
318
319 >>> p = Pet('Lucy', Pet.Cat)
320 >>> p.type
321 Kind.Cat
322 >>> int(p.type)
323 1L
324
325
Wenzel Jakob93296692015-10-13 23:21:54 +0200326.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.