blob: 30fb2a2d5fb28bf8606b20c526d806f05de499a1 [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
Dean Moldovan57a9bbc2017-01-31 16:54:08 +010041:class:`class_` creates bindings for a C++ *class* or *struct*-style data
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020042structure. :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
Dean Moldovan4e959c92016-12-08 11:07:52 +0100107.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.
108
Wenzel Jakobf88af0c2016-06-22 13:52:31 +0200109.. _properties:
110
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200111Instance and static fields
112==========================
113
114We can also directly expose the ``name`` field using the
115:func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
116method also exists for ``const`` fields.
117
118.. code-block:: cpp
119
120 py::class_<Pet>(m, "Pet")
121 .def(py::init<const std::string &>())
122 .def_readwrite("name", &Pet::name)
123 // ... remainder ...
124
125This makes it possible to write
126
Wenzel Jakob99279f72016-06-03 11:19:29 +0200127.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200128
129 >>> p = example.Pet('Molly')
130 >>> p.name
131 u'Molly'
132 >>> p.name = 'Charly'
133 >>> p.name
134 u'Charly'
135
136Now suppose that ``Pet::name`` was a private internal variable
137that can only be accessed via setters and getters.
138
139.. code-block:: cpp
140
141 class Pet {
142 public:
143 Pet(const std::string &name) : name(name) { }
144 void setName(const std::string &name_) { name = name_; }
145 const std::string &getName() const { return name; }
146 private:
147 std::string name;
148 };
149
150In this case, the method :func:`class_::def_property`
151(:func:`class_::def_property_readonly` for read-only data) can be used to
Wenzel Jakob93296692015-10-13 23:21:54 +0200152provide a field-like interface within Python that will transparently call
153the setter and getter functions:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200154
155.. code-block:: cpp
156
157 py::class_<Pet>(m, "Pet")
158 .def(py::init<const std::string &>())
159 .def_property("name", &Pet::getName, &Pet::setName)
160 // ... remainder ...
161
162.. seealso::
163
164 Similar functions :func:`class_::def_readwrite_static`,
165 :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
166 and :func:`class_::def_property_readonly_static` are provided for binding
Wenzel Jakobf88af0c2016-06-22 13:52:31 +0200167 static variables and properties. Please also see the section on
168 :ref:`static_properties` in the advanced part of the documentation.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200169
Dean Moldovan9273af42016-10-13 23:53:16 +0200170Dynamic attributes
171==================
172
173Native Python classes can pick up new attributes dynamically:
174
175.. code-block:: pycon
176
177 >>> class Pet:
178 ... name = 'Molly'
179 ...
180 >>> p = Pet()
181 >>> p.name = 'Charly' # overwrite existing
182 >>> p.age = 2 # dynamically add a new attribute
183
184By default, classes exported from C++ do not support this and the only writable
185attributes are the ones explicitly defined using :func:`class_::def_readwrite`
186or :func:`class_::def_property`.
187
188.. code-block:: cpp
189
190 py::class_<Pet>(m, "Pet")
191 .def(py::init<>())
192 .def_readwrite("name", &Pet::name);
193
194Trying to set any other attribute results in an error:
195
196.. code-block:: pycon
197
198 >>> p = example.Pet()
199 >>> p.name = 'Charly' # OK, attribute defined in C++
200 >>> p.age = 2 # fail
201 AttributeError: 'Pet' object has no attribute 'age'
202
203To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
204must be added to the :class:`py::class_` constructor:
205
206.. code-block:: cpp
207
208 py::class_<Pet>(m, "Pet", py::dynamic_attr())
209 .def(py::init<>())
210 .def_readwrite("name", &Pet::name);
211
212Now everything works as expected:
213
214.. code-block:: pycon
215
216 >>> p = example.Pet()
217 >>> p.name = 'Charly' # OK, overwrite value in C++
218 >>> p.age = 2 # OK, dynamically add a new attribute
219 >>> p.__dict__ # just like a native Python class
220 {'age': 2}
221
222Note that there is a small runtime cost for a class with dynamic attributes.
223Not only because of the addition of a ``__dict__``, but also because of more
224expensive garbage collection tracking which must be activated to resolve
225possible circular references. Native Python classes incur this same cost by
226default, so this is not anything to worry about. By default, pybind11 classes
227are more efficient than native Python classes. Enabling dynamic attributes
228just brings them on par.
229
Wenzel Jakob2dfbade2016-01-17 22:36:37 +0100230.. _inheritance:
231
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200232Inheritance
233===========
234
235Suppose now that the example consists of two data structures with an
236inheritance relationship:
237
238.. code-block:: cpp
239
240 struct Pet {
241 Pet(const std::string &name) : name(name) { }
242 std::string name;
243 };
244
245 struct Dog : Pet {
246 Dog(const std::string &name) : Pet(name) { }
247 std::string bark() const { return "woof!"; }
248 };
249
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900250There are two different ways of indicating a hierarchical relationship to
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400251pybind11: the first specifies the C++ base class as an extra template
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900252parameter of the :class:`class_`:
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100253
254.. code-block:: cpp
255
256 py::class_<Pet>(m, "Pet")
257 .def(py::init<const std::string &>())
258 .def_readwrite("name", &Pet::name);
259
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400260 // Method 1: template parameter:
261 py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
262 .def(py::init<const std::string &>())
263 .def("bark", &Dog::bark);
264
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100265Alternatively, we can also assign a name to the previously bound ``Pet``
266:class:`class_` object and reference it when binding the ``Dog`` class:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200267
268.. code-block:: cpp
269
270 py::class_<Pet> pet(m, "Pet");
271 pet.def(py::init<const std::string &>())
272 .def_readwrite("name", &Pet::name);
273
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900274 // Method 2: pass parent class_ object:
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100275 py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200276 .def(py::init<const std::string &>())
277 .def("bark", &Dog::bark);
278
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900279Functionality-wise, both approaches are equivalent. Afterwards, instances will
280expose fields and methods of both types:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200281
Wenzel Jakob99279f72016-06-03 11:19:29 +0200282.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200283
284 >>> p = example.Dog('Molly')
285 >>> p.name
286 u'Molly'
287 >>> p.bark()
288 u'woof!'
289
290Overloaded methods
291==================
292
293Sometimes there are several overloaded C++ methods with the same name taking
294different kinds of input arguments:
295
296.. code-block:: cpp
297
298 struct Pet {
299 Pet(const std::string &name, int age) : name(name), age(age) { }
300
myd73499b815ad2017-01-13 18:15:52 +0800301 void set(int age_) { age = age_; }
302 void set(const std::string &name_) { name = name_; }
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200303
304 std::string name;
305 int age;
306 };
307
308Attempting to bind ``Pet::set`` will cause an error since the compiler does not
309know which method the user intended to select. We can disambiguate by casting
310them to function pointers. Binding multiple functions to the same Python name
Wenzel Jakob0fb85282015-10-19 23:50:51 +0200311automatically creates a chain of function overloads that will be tried in
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200312sequence.
313
314.. code-block:: cpp
315
316 py::class_<Pet>(m, "Pet")
317 .def(py::init<const std::string &, int>())
318 .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
319 .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
320
321The overload signatures are also visible in the method's docstring:
322
Wenzel Jakob99279f72016-06-03 11:19:29 +0200323.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200324
325 >>> help(example.Pet)
326
327 class Pet(__builtin__.object)
328 | Methods defined here:
329 |
330 | __init__(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100331 | Signature : (Pet, str, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200332 |
333 | set(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100334 | 1. Signature : (Pet, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200335 |
336 | Set the pet's age
337 |
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100338 | 2. Signature : (Pet, str) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200339 |
340 | Set the pet's name
Wenzel Jakob93296692015-10-13 23:21:54 +0200341
Dean Moldovan4e959c92016-12-08 11:07:52 +0100342If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
343syntax to cast the overloaded function:
344
345.. code-block:: cpp
346
347 py::class_<Pet>(m, "Pet")
348 .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
349 .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
350
351Here, ``py::overload_cast`` only requires the parameter types to be specified.
352The return type and class are deduced. This avoids the additional noise of
353``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
354on constness, the ``py::const_`` tag should be used:
355
356.. code-block:: cpp
357
358 struct Widget {
359 int foo(int x, float y);
360 int foo(int x, float y) const;
361 };
362
363 py::class_<Widget>(m, "Widget")
364 .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
365 .def("foo_const", py::overload_cast<int, float>(&Widget::foo, py::const_));
366
367
368.. [#cpp14] A compiler which supports the ``-std=c++14`` flag
369 or Visual Studio 2015 Update 2 and newer.
370
Wenzel Jakob93296692015-10-13 23:21:54 +0200371.. note::
372
373 To define multiple overloaded constructors, simply declare one after the
374 other using the ``.def(py::init<...>())`` syntax. The existing machinery
375 for specifying keyword and default arguments also works.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200376
377Enumerations and internal types
378===============================
379
Wenzel Jakob93296692015-10-13 23:21:54 +0200380Let's now suppose that the example class contains an internal enumeration type,
381e.g.:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200382
383.. code-block:: cpp
384
385 struct Pet {
386 enum Kind {
387 Dog = 0,
388 Cat
389 };
390
391 Pet(const std::string &name, Kind type) : name(name), type(type) { }
392
393 std::string name;
394 Kind type;
395 };
396
397The binding code for this example looks as follows:
398
399.. code-block:: cpp
400
401 py::class_<Pet> pet(m, "Pet");
402
403 pet.def(py::init<const std::string &, Pet::Kind>())
404 .def_readwrite("name", &Pet::name)
405 .def_readwrite("type", &Pet::type);
406
407 py::enum_<Pet::Kind>(pet, "Kind")
408 .value("Dog", Pet::Kind::Dog)
409 .value("Cat", Pet::Kind::Cat)
410 .export_values();
411
412To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
413``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
Wenzel Jakob93296692015-10-13 23:21:54 +0200414constructor. The :func:`enum_::export_values` function exports the enum entries
415into the parent scope, which should be skipped for newer C++11-style strongly
416typed enums.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200417
Wenzel Jakob99279f72016-06-03 11:19:29 +0200418.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200419
420 >>> p = Pet('Lucy', Pet.Cat)
421 >>> p.type
422 Kind.Cat
423 >>> int(p.type)
424 1L
425
Matthieu Becaf936e12017-03-03 08:45:50 -0800426The entries defined by the enumeration type are exposed in the ``__members__`` property:
427
428.. code-block:: pycon
429
430 >>> Pet.Kind.__members__
431 {'Dog': Kind.Dog, 'Cat': Kind.Cat}
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200432
Wenzel Jakob405f6d12016-11-17 23:24:47 +0100433.. note::
434
435 When the special tag ``py::arithmetic()`` is specified to the ``enum_``
436 constructor, pybind11 creates an enumeration that also supports rudimentary
437 arithmetic and bit-level operations like comparisons, and, or, xor, negation,
438 etc.
439
440 .. code-block:: cpp
441
442 py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
443 ...
444
445 By default, these are omitted to conserve space.