blob: 4270b8d6d623d0f6c4728efeaec37e393de98f23 [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 Jakobbad589a2016-09-12 12:03:20 +0900188There are two different ways of indicating a hierarchical relationship to
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400189pybind11: the first specifies the C++ base class as an extra template
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900190parameter of the :class:`class_`:
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100191
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
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400198 // Method 1: template parameter:
199 py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
200 .def(py::init<const std::string &>())
201 .def("bark", &Dog::bark);
202
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100203Alternatively, we can also assign a name to the previously bound ``Pet``
204:class:`class_` object and reference it when binding the ``Dog`` class:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200205
206.. code-block:: cpp
207
208 py::class_<Pet> pet(m, "Pet");
209 pet.def(py::init<const std::string &>())
210 .def_readwrite("name", &Pet::name);
211
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900212 // Method 2: pass parent class_ object:
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100213 py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200214 .def(py::init<const std::string &>())
215 .def("bark", &Dog::bark);
216
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900217Functionality-wise, both approaches are equivalent. Afterwards, instances will
218expose fields and methods of both types:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200219
Wenzel Jakob99279f72016-06-03 11:19:29 +0200220.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200221
222 >>> p = example.Dog('Molly')
223 >>> p.name
224 u'Molly'
225 >>> p.bark()
226 u'woof!'
227
228Overloaded methods
229==================
230
231Sometimes there are several overloaded C++ methods with the same name taking
232different kinds of input arguments:
233
234.. code-block:: cpp
235
236 struct Pet {
237 Pet(const std::string &name, int age) : name(name), age(age) { }
238
239 void set(int age) { age = age; }
240 void set(const std::string &name) { name = name; }
241
242 std::string name;
243 int age;
244 };
245
246Attempting to bind ``Pet::set`` will cause an error since the compiler does not
247know which method the user intended to select. We can disambiguate by casting
248them to function pointers. Binding multiple functions to the same Python name
Wenzel Jakob0fb85282015-10-19 23:50:51 +0200249automatically creates a chain of function overloads that will be tried in
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200250sequence.
251
252.. code-block:: cpp
253
254 py::class_<Pet>(m, "Pet")
255 .def(py::init<const std::string &, int>())
256 .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
257 .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
258
259The overload signatures are also visible in the method's docstring:
260
Wenzel Jakob99279f72016-06-03 11:19:29 +0200261.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200262
263 >>> help(example.Pet)
264
265 class Pet(__builtin__.object)
266 | Methods defined here:
267 |
268 | __init__(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100269 | Signature : (Pet, str, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200270 |
271 | set(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100272 | 1. Signature : (Pet, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200273 |
274 | Set the pet's age
275 |
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100276 | 2. Signature : (Pet, str) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200277 |
278 | Set the pet's name
Wenzel Jakob93296692015-10-13 23:21:54 +0200279
280.. note::
281
282 To define multiple overloaded constructors, simply declare one after the
283 other using the ``.def(py::init<...>())`` syntax. The existing machinery
284 for specifying keyword and default arguments also works.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200285
286Enumerations and internal types
287===============================
288
Wenzel Jakob93296692015-10-13 23:21:54 +0200289Let's now suppose that the example class contains an internal enumeration type,
290e.g.:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200291
292.. code-block:: cpp
293
294 struct Pet {
295 enum Kind {
296 Dog = 0,
297 Cat
298 };
299
300 Pet(const std::string &name, Kind type) : name(name), type(type) { }
301
302 std::string name;
303 Kind type;
304 };
305
306The binding code for this example looks as follows:
307
308.. code-block:: cpp
309
310 py::class_<Pet> pet(m, "Pet");
311
312 pet.def(py::init<const std::string &, Pet::Kind>())
313 .def_readwrite("name", &Pet::name)
314 .def_readwrite("type", &Pet::type);
315
316 py::enum_<Pet::Kind>(pet, "Kind")
317 .value("Dog", Pet::Kind::Dog)
318 .value("Cat", Pet::Kind::Cat)
319 .export_values();
320
321To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
322``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
Wenzel Jakob93296692015-10-13 23:21:54 +0200323constructor. The :func:`enum_::export_values` function exports the enum entries
324into the parent scope, which should be skipped for newer C++11-style strongly
325typed enums.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200326
Wenzel Jakob99279f72016-06-03 11:19:29 +0200327.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200328
329 >>> p = Pet('Lucy', Pet.Cat)
330 >>> p.type
331 Kind.Cat
332 >>> int(p.type)
333 1L
334
335
Wenzel Jakob93296692015-10-13 23:21:54 +0200336.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.