blob: ca2477e83eb699bd30260f4099b5f0c8f38e7dd5 [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
Dean Moldovan443ab592017-04-24 01:51:44 +020030 PYBIND11_MODULE(example, m) {
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020031 py::class_<Pet>(m, "Pet")
32 .def(py::init<const std::string &>())
33 .def("setName", &Pet::setName)
34 .def("getName", &Pet::getName);
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020035 }
36
Dean Moldovan57a9bbc2017-01-31 16:54:08 +010037:class:`class_` creates bindings for a C++ *class* or *struct*-style data
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020038structure. :func:`init` is a convenience function that takes the types of a
39constructor's parameters as template arguments and wraps the corresponding
40constructor (see the :ref:`custom_constructors` section for details). An
41interactive Python session demonstrating this example is shown below:
42
Wenzel Jakob99279f72016-06-03 11:19:29 +020043.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020044
45 % python
46 >>> import example
47 >>> p = example.Pet('Molly')
48 >>> print(p)
49 <example.Pet object at 0x10cd98060>
50 >>> p.getName()
51 u'Molly'
52 >>> p.setName('Charly')
53 >>> p.getName()
54 u'Charly'
55
Wenzel Jakob43b6a232016-02-07 17:24:41 +010056.. seealso::
57
58 Static member functions can be bound in the same way using
59 :func:`class_::def_static`.
60
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020061Keyword and default arguments
62=============================
63It is possible to specify keyword and default arguments using the syntax
64discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
65and :ref:`default_args` for details.
66
67Binding lambda functions
68========================
69
70Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
71
Wenzel Jakob99279f72016-06-03 11:19:29 +020072.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020073
74 >>> print(p)
75 <example.Pet object at 0x10cd98060>
76
77To address this, we could bind an utility function that returns a human-readable
78summary to the special method slot named ``__repr__``. Unfortunately, there is no
79suitable functionality in the ``Pet`` data structure, and it would be nice if
80we did not have to change it. This can easily be accomplished by binding a
81Lambda function instead:
82
83.. code-block:: cpp
84
85 py::class_<Pet>(m, "Pet")
86 .def(py::init<const std::string &>())
87 .def("setName", &Pet::setName)
88 .def("getName", &Pet::getName)
89 .def("__repr__",
90 [](const Pet &a) {
91 return "<example.Pet named '" + a.name + "'>";
92 }
93 );
94
95Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
96With the above change, the same Python code now produces the following output:
97
Wenzel Jakob99279f72016-06-03 11:19:29 +020098.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020099
100 >>> print(p)
101 <example.Pet named 'Molly'>
102
Dean Moldovan4e959c92016-12-08 11:07:52 +0100103.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.
104
Wenzel Jakobf88af0c2016-06-22 13:52:31 +0200105.. _properties:
106
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200107Instance and static fields
108==========================
109
110We can also directly expose the ``name`` field using the
111:func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
112method also exists for ``const`` fields.
113
114.. code-block:: cpp
115
116 py::class_<Pet>(m, "Pet")
117 .def(py::init<const std::string &>())
118 .def_readwrite("name", &Pet::name)
119 // ... remainder ...
120
121This makes it possible to write
122
Wenzel Jakob99279f72016-06-03 11:19:29 +0200123.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200124
125 >>> p = example.Pet('Molly')
126 >>> p.name
127 u'Molly'
128 >>> p.name = 'Charly'
129 >>> p.name
130 u'Charly'
131
132Now suppose that ``Pet::name`` was a private internal variable
133that can only be accessed via setters and getters.
134
135.. code-block:: cpp
136
137 class Pet {
138 public:
139 Pet(const std::string &name) : name(name) { }
140 void setName(const std::string &name_) { name = name_; }
141 const std::string &getName() const { return name; }
142 private:
143 std::string name;
144 };
145
146In this case, the method :func:`class_::def_property`
147(:func:`class_::def_property_readonly` for read-only data) can be used to
Wenzel Jakob93296692015-10-13 23:21:54 +0200148provide a field-like interface within Python that will transparently call
149the setter and getter functions:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200150
151.. code-block:: cpp
152
153 py::class_<Pet>(m, "Pet")
154 .def(py::init<const std::string &>())
155 .def_property("name", &Pet::getName, &Pet::setName)
156 // ... remainder ...
157
158.. seealso::
159
160 Similar functions :func:`class_::def_readwrite_static`,
161 :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
162 and :func:`class_::def_property_readonly_static` are provided for binding
Wenzel Jakobf88af0c2016-06-22 13:52:31 +0200163 static variables and properties. Please also see the section on
164 :ref:`static_properties` in the advanced part of the documentation.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200165
Dean Moldovan9273af42016-10-13 23:53:16 +0200166Dynamic attributes
167==================
168
169Native Python classes can pick up new attributes dynamically:
170
171.. code-block:: pycon
172
173 >>> class Pet:
174 ... name = 'Molly'
175 ...
176 >>> p = Pet()
177 >>> p.name = 'Charly' # overwrite existing
178 >>> p.age = 2 # dynamically add a new attribute
179
180By default, classes exported from C++ do not support this and the only writable
181attributes are the ones explicitly defined using :func:`class_::def_readwrite`
182or :func:`class_::def_property`.
183
184.. code-block:: cpp
185
186 py::class_<Pet>(m, "Pet")
187 .def(py::init<>())
188 .def_readwrite("name", &Pet::name);
189
190Trying to set any other attribute results in an error:
191
192.. code-block:: pycon
193
194 >>> p = example.Pet()
195 >>> p.name = 'Charly' # OK, attribute defined in C++
196 >>> p.age = 2 # fail
197 AttributeError: 'Pet' object has no attribute 'age'
198
199To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
200must be added to the :class:`py::class_` constructor:
201
202.. code-block:: cpp
203
204 py::class_<Pet>(m, "Pet", py::dynamic_attr())
205 .def(py::init<>())
206 .def_readwrite("name", &Pet::name);
207
208Now everything works as expected:
209
210.. code-block:: pycon
211
212 >>> p = example.Pet()
213 >>> p.name = 'Charly' # OK, overwrite value in C++
214 >>> p.age = 2 # OK, dynamically add a new attribute
215 >>> p.__dict__ # just like a native Python class
216 {'age': 2}
217
218Note that there is a small runtime cost for a class with dynamic attributes.
219Not only because of the addition of a ``__dict__``, but also because of more
220expensive garbage collection tracking which must be activated to resolve
221possible circular references. Native Python classes incur this same cost by
222default, so this is not anything to worry about. By default, pybind11 classes
223are more efficient than native Python classes. Enabling dynamic attributes
224just brings them on par.
225
Wenzel Jakob2dfbade2016-01-17 22:36:37 +0100226.. _inheritance:
227
Dustin Spicuzza7c0e2c22017-07-22 21:36:08 -0400228Inheritance and automatic upcasting
229===================================
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200230
231Suppose now that the example consists of two data structures with an
232inheritance relationship:
233
234.. code-block:: cpp
235
236 struct Pet {
237 Pet(const std::string &name) : name(name) { }
238 std::string name;
239 };
240
241 struct Dog : Pet {
242 Dog(const std::string &name) : Pet(name) { }
243 std::string bark() const { return "woof!"; }
244 };
245
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900246There are two different ways of indicating a hierarchical relationship to
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400247pybind11: the first specifies the C++ base class as an extra template
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900248parameter of the :class:`class_`:
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100249
250.. code-block:: cpp
251
252 py::class_<Pet>(m, "Pet")
253 .def(py::init<const std::string &>())
254 .def_readwrite("name", &Pet::name);
255
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400256 // Method 1: template parameter:
257 py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
258 .def(py::init<const std::string &>())
259 .def("bark", &Dog::bark);
260
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100261Alternatively, we can also assign a name to the previously bound ``Pet``
262:class:`class_` object and reference it when binding the ``Dog`` class:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200263
264.. code-block:: cpp
265
266 py::class_<Pet> pet(m, "Pet");
267 pet.def(py::init<const std::string &>())
268 .def_readwrite("name", &Pet::name);
269
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900270 // Method 2: pass parent class_ object:
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100271 py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200272 .def(py::init<const std::string &>())
273 .def("bark", &Dog::bark);
274
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900275Functionality-wise, both approaches are equivalent. Afterwards, instances will
276expose fields and methods of both types:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200277
Wenzel Jakob99279f72016-06-03 11:19:29 +0200278.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200279
280 >>> p = example.Dog('Molly')
281 >>> p.name
282 u'Molly'
283 >>> p.bark()
284 u'woof!'
285
Dustin Spicuzza7c0e2c22017-07-22 21:36:08 -0400286The C++ classes defined above are regular non-polymorphic types with an
287inheritance relationship. This is reflected in Python:
288
289.. code-block:: cpp
290
291 // Return a base pointer to a derived instance
292 m.def("pet_store", []() { return std::unique_ptr<Pet>(new Dog("Molly")); });
293
294.. code-block:: pycon
295
296 >>> p = example.pet_store()
297 >>> type(p) # `Dog` instance behind `Pet` pointer
298 Pet # no pointer upcasting for regular non-polymorphic types
299 >>> p.bark()
300 AttributeError: 'Pet' object has no attribute 'bark'
301
302The function returned a ``Dog`` instance, but because it's a non-polymorphic
303type behind a base pointer, Python only sees a ``Pet``. In C++, a type is only
304considered polymorphic if it has at least one virtual function and pybind11
305will automatically recognize this:
306
307.. code-block:: cpp
308
309 struct PolymorphicPet {
310 virtual ~PolymorphicPet() = default;
311 };
312
313 struct PolymorphicDog : PolymorphicPet {
314 std::string bark() const { return "woof!"; }
315 };
316
317 // Same binding code
318 py::class_<PolymorphicPet>(m, "PolymorphicPet");
319 py::class_<PolymorphicDog, PolymorphicPet>(m, "PolymorphicDog")
320 .def(py::init<>())
321 .def("bark", &PolymorphicDog::bark);
322
323 // Again, return a base pointer to a derived instance
324 m.def("pet_store2", []() { return std::unique_ptr<PolymorphicPet>(new PolymorphicDog); });
325
326.. code-block:: pycon
327
328 >>> p = example.pet_store2()
329 >>> type(p)
330 PolymorphicDog # automatically upcast
331 >>> p.bark()
332 u'woof!'
333
334Given a pointer to a polymorphic base, pybind11 performs automatic upcasting
335to the actual derived type. Note that this goes beyond the usual situation in
336C++: we don't just get access to the virtual functions of the base, we get the
337concrete derived type including functions and attributes that the base type may
338not even be aware of.
339
340.. seealso::
341
342 For more information about polymorphic behavior see :ref:`overriding_virtuals`.
343
344
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200345Overloaded methods
346==================
347
348Sometimes there are several overloaded C++ methods with the same name taking
349different kinds of input arguments:
350
351.. code-block:: cpp
352
353 struct Pet {
354 Pet(const std::string &name, int age) : name(name), age(age) { }
355
myd73499b815ad2017-01-13 18:15:52 +0800356 void set(int age_) { age = age_; }
357 void set(const std::string &name_) { name = name_; }
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200358
359 std::string name;
360 int age;
361 };
362
363Attempting to bind ``Pet::set`` will cause an error since the compiler does not
364know which method the user intended to select. We can disambiguate by casting
365them to function pointers. Binding multiple functions to the same Python name
Wenzel Jakob0fb85282015-10-19 23:50:51 +0200366automatically creates a chain of function overloads that will be tried in
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200367sequence.
368
369.. code-block:: cpp
370
371 py::class_<Pet>(m, "Pet")
372 .def(py::init<const std::string &, int>())
373 .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
374 .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
375
376The overload signatures are also visible in the method's docstring:
377
Wenzel Jakob99279f72016-06-03 11:19:29 +0200378.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200379
380 >>> help(example.Pet)
381
382 class Pet(__builtin__.object)
383 | Methods defined here:
384 |
385 | __init__(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100386 | Signature : (Pet, str, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200387 |
388 | set(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100389 | 1. Signature : (Pet, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200390 |
391 | Set the pet's age
392 |
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100393 | 2. Signature : (Pet, str) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200394 |
395 | Set the pet's name
Wenzel Jakob93296692015-10-13 23:21:54 +0200396
Dean Moldovan4e959c92016-12-08 11:07:52 +0100397If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
398syntax to cast the overloaded function:
399
400.. code-block:: cpp
401
402 py::class_<Pet>(m, "Pet")
403 .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
404 .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
405
406Here, ``py::overload_cast`` only requires the parameter types to be specified.
407The return type and class are deduced. This avoids the additional noise of
408``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
409on constness, the ``py::const_`` tag should be used:
410
411.. code-block:: cpp
412
413 struct Widget {
414 int foo(int x, float y);
415 int foo(int x, float y) const;
416 };
417
418 py::class_<Widget>(m, "Widget")
419 .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
420 .def("foo_const", py::overload_cast<int, float>(&Widget::foo, py::const_));
421
422
423.. [#cpp14] A compiler which supports the ``-std=c++14`` flag
424 or Visual Studio 2015 Update 2 and newer.
425
Wenzel Jakob93296692015-10-13 23:21:54 +0200426.. note::
427
428 To define multiple overloaded constructors, simply declare one after the
429 other using the ``.def(py::init<...>())`` syntax. The existing machinery
430 for specifying keyword and default arguments also works.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200431
432Enumerations and internal types
433===============================
434
Wenzel Jakob93296692015-10-13 23:21:54 +0200435Let's now suppose that the example class contains an internal enumeration type,
436e.g.:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200437
438.. code-block:: cpp
439
440 struct Pet {
441 enum Kind {
442 Dog = 0,
443 Cat
444 };
445
446 Pet(const std::string &name, Kind type) : name(name), type(type) { }
447
448 std::string name;
449 Kind type;
450 };
451
452The binding code for this example looks as follows:
453
454.. code-block:: cpp
455
456 py::class_<Pet> pet(m, "Pet");
457
458 pet.def(py::init<const std::string &, Pet::Kind>())
459 .def_readwrite("name", &Pet::name)
460 .def_readwrite("type", &Pet::type);
461
462 py::enum_<Pet::Kind>(pet, "Kind")
463 .value("Dog", Pet::Kind::Dog)
464 .value("Cat", Pet::Kind::Cat)
465 .export_values();
466
467To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
468``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
Wenzel Jakob93296692015-10-13 23:21:54 +0200469constructor. The :func:`enum_::export_values` function exports the enum entries
470into the parent scope, which should be skipped for newer C++11-style strongly
471typed enums.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200472
Wenzel Jakob99279f72016-06-03 11:19:29 +0200473.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200474
475 >>> p = Pet('Lucy', Pet.Cat)
476 >>> p.type
477 Kind.Cat
478 >>> int(p.type)
479 1L
480
Matthieu Becaf936e12017-03-03 08:45:50 -0800481The entries defined by the enumeration type are exposed in the ``__members__`` property:
482
483.. code-block:: pycon
484
485 >>> Pet.Kind.__members__
486 {'Dog': Kind.Dog, 'Cat': Kind.Cat}
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200487
Wenzel Jakob405f6d12016-11-17 23:24:47 +0100488.. note::
489
490 When the special tag ``py::arithmetic()`` is specified to the ``enum_``
491 constructor, pybind11 creates an enumeration that also supports rudimentary
492 arithmetic and bit-level operations like comparisons, and, or, xor, negation,
493 etc.
494
495 .. code-block:: cpp
496
497 py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
498 ...
499
500 By default, these are omitted to conserve space.