blob: 5afb21edcad9fb6c34d0e776ee807a87d1ee3816 [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
Wenzel Jakob99279f72016-06-03 11:19:29 +020047.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020048
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
Wenzel Jakob43b6a232016-02-07 17:24:41 +010060.. seealso::
61
62 Static member functions can be bound in the same way using
63 :func:`class_::def_static`.
64
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020065Keyword and default arguments
66=============================
67It is possible to specify keyword and default arguments using the syntax
68discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
69and :ref:`default_args` for details.
70
71Binding lambda functions
72========================
73
74Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
75
Wenzel Jakob99279f72016-06-03 11:19:29 +020076.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020077
78 >>> print(p)
79 <example.Pet object at 0x10cd98060>
80
81To address this, we could bind an utility function that returns a human-readable
82summary to the special method slot named ``__repr__``. Unfortunately, there is no
83suitable functionality in the ``Pet`` data structure, and it would be nice if
84we did not have to change it. This can easily be accomplished by binding a
85Lambda function instead:
86
87.. code-block:: cpp
88
89 py::class_<Pet>(m, "Pet")
90 .def(py::init<const std::string &>())
91 .def("setName", &Pet::setName)
92 .def("getName", &Pet::getName)
93 .def("__repr__",
94 [](const Pet &a) {
95 return "<example.Pet named '" + a.name + "'>";
96 }
97 );
98
99Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
100With the above change, the same Python code now produces the following output:
101
Wenzel Jakob99279f72016-06-03 11:19:29 +0200102.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200103
104 >>> print(p)
105 <example.Pet named 'Molly'>
106
Wenzel Jakobf88af0c2016-06-22 13:52:31 +0200107.. _properties:
108
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200109Instance and static fields
110==========================
111
112We can also directly expose the ``name`` field using the
113:func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
114method also exists for ``const`` fields.
115
116.. code-block:: cpp
117
118 py::class_<Pet>(m, "Pet")
119 .def(py::init<const std::string &>())
120 .def_readwrite("name", &Pet::name)
121 // ... remainder ...
122
123This makes it possible to write
124
Wenzel Jakob99279f72016-06-03 11:19:29 +0200125.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200126
127 >>> p = example.Pet('Molly')
128 >>> p.name
129 u'Molly'
130 >>> p.name = 'Charly'
131 >>> p.name
132 u'Charly'
133
134Now suppose that ``Pet::name`` was a private internal variable
135that can only be accessed via setters and getters.
136
137.. code-block:: cpp
138
139 class Pet {
140 public:
141 Pet(const std::string &name) : name(name) { }
142 void setName(const std::string &name_) { name = name_; }
143 const std::string &getName() const { return name; }
144 private:
145 std::string name;
146 };
147
148In this case, the method :func:`class_::def_property`
149(:func:`class_::def_property_readonly` for read-only data) can be used to
Wenzel Jakob93296692015-10-13 23:21:54 +0200150provide a field-like interface within Python that will transparently call
151the setter and getter functions:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200152
153.. code-block:: cpp
154
155 py::class_<Pet>(m, "Pet")
156 .def(py::init<const std::string &>())
157 .def_property("name", &Pet::getName, &Pet::setName)
158 // ... remainder ...
159
160.. seealso::
161
162 Similar functions :func:`class_::def_readwrite_static`,
163 :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
164 and :func:`class_::def_property_readonly_static` are provided for binding
Wenzel Jakobf88af0c2016-06-22 13:52:31 +0200165 static variables and properties. Please also see the section on
166 :ref:`static_properties` in the advanced part of the documentation.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200167
Wenzel Jakob2dfbade2016-01-17 22:36:37 +0100168.. _inheritance:
169
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200170Inheritance
171===========
172
173Suppose now that the example consists of two data structures with an
174inheritance relationship:
175
176.. code-block:: cpp
177
178 struct Pet {
179 Pet(const std::string &name) : name(name) { }
180 std::string name;
181 };
182
183 struct Dog : Pet {
184 Dog(const std::string &name) : Pet(name) { }
185 std::string bark() const { return "woof!"; }
186 };
187
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100188There are two different ways of indicating a hierarchical relationship to
189pybind11: the first is by specifying the C++ base class explicitly during
190construction using the ``base`` attribute:
191
192.. code-block:: cpp
193
194 py::class_<Pet>(m, "Pet")
195 .def(py::init<const std::string &>())
196 .def_readwrite("name", &Pet::name);
197
198 py::class_<Dog>(m, "Dog", py::base<Pet>() /* <- specify C++ parent type */)
199 .def(py::init<const std::string &>())
200 .def("bark", &Dog::bark);
201
202Alternatively, we can also assign a name to the previously bound ``Pet``
203:class:`class_` object and reference it when binding the ``Dog`` class:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200204
205.. code-block:: cpp
206
207 py::class_<Pet> pet(m, "Pet");
208 pet.def(py::init<const std::string &>())
209 .def_readwrite("name", &Pet::name);
210
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100211 py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200212 .def(py::init<const std::string &>())
213 .def("bark", &Dog::bark);
214
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100215Functionality-wise, both approaches are completely equivalent. Afterwards,
216instances will expose fields and methods of both types:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200217
Wenzel Jakob99279f72016-06-03 11:19:29 +0200218.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200219
220 >>> p = example.Dog('Molly')
221 >>> p.name
222 u'Molly'
223 >>> p.bark()
224 u'woof!'
225
226Overloaded methods
227==================
228
229Sometimes there are several overloaded C++ methods with the same name taking
230different kinds of input arguments:
231
232.. code-block:: cpp
233
234 struct Pet {
235 Pet(const std::string &name, int age) : name(name), age(age) { }
236
237 void set(int age) { age = age; }
238 void set(const std::string &name) { name = name; }
239
240 std::string name;
241 int age;
242 };
243
244Attempting to bind ``Pet::set`` will cause an error since the compiler does not
245know which method the user intended to select. We can disambiguate by casting
246them to function pointers. Binding multiple functions to the same Python name
Wenzel Jakob0fb85282015-10-19 23:50:51 +0200247automatically creates a chain of function overloads that will be tried in
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200248sequence.
249
250.. code-block:: cpp
251
252 py::class_<Pet>(m, "Pet")
253 .def(py::init<const std::string &, int>())
254 .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
255 .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
256
257The overload signatures are also visible in the method's docstring:
258
Wenzel Jakob99279f72016-06-03 11:19:29 +0200259.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200260
261 >>> help(example.Pet)
262
263 class Pet(__builtin__.object)
264 | Methods defined here:
265 |
266 | __init__(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100267 | Signature : (Pet, str, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200268 |
269 | set(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100270 | 1. Signature : (Pet, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200271 |
272 | Set the pet's age
273 |
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100274 | 2. Signature : (Pet, str) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200275 |
276 | Set the pet's name
Wenzel Jakob93296692015-10-13 23:21:54 +0200277
278.. note::
279
280 To define multiple overloaded constructors, simply declare one after the
281 other using the ``.def(py::init<...>())`` syntax. The existing machinery
282 for specifying keyword and default arguments also works.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200283
284Enumerations and internal types
285===============================
286
Wenzel Jakob93296692015-10-13 23:21:54 +0200287Let's now suppose that the example class contains an internal enumeration type,
288e.g.:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200289
290.. code-block:: cpp
291
292 struct Pet {
293 enum Kind {
294 Dog = 0,
295 Cat
296 };
297
298 Pet(const std::string &name, Kind type) : name(name), type(type) { }
299
300 std::string name;
301 Kind type;
302 };
303
304The binding code for this example looks as follows:
305
306.. code-block:: cpp
307
308 py::class_<Pet> pet(m, "Pet");
309
310 pet.def(py::init<const std::string &, Pet::Kind>())
311 .def_readwrite("name", &Pet::name)
312 .def_readwrite("type", &Pet::type);
313
314 py::enum_<Pet::Kind>(pet, "Kind")
315 .value("Dog", Pet::Kind::Dog)
316 .value("Cat", Pet::Kind::Cat)
317 .export_values();
318
319To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
320``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
Wenzel Jakob93296692015-10-13 23:21:54 +0200321constructor. The :func:`enum_::export_values` function exports the enum entries
322into the parent scope, which should be skipped for newer C++11-style strongly
323typed enums.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200324
Wenzel Jakob99279f72016-06-03 11:19:29 +0200325.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200326
327 >>> p = Pet('Lucy', Pet.Cat)
328 >>> p.type
329 Kind.Cat
330 >>> int(p.type)
331 1L
332
333
Wenzel Jakob93296692015-10-13 23:21:54 +0200334.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.