blob: 80f378f68f2cc56702378f20a8895b94b51a452b [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
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400188There are three different ways of indicating a hierarchical relationship to
189pybind11: the first specifies the C++ base class as an extra template
190parameter of the :class:`class_`; the second uses a special ``base`` attribute
191passed into the constructor:
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100192
193.. code-block:: cpp
194
195 py::class_<Pet>(m, "Pet")
196 .def(py::init<const std::string &>())
197 .def_readwrite("name", &Pet::name);
198
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400199 // Method 1: template parameter:
200 py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
201 .def(py::init<const std::string &>())
202 .def("bark", &Dog::bark);
203
204 // Method 2: py::base attribute:
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100205 py::class_<Dog>(m, "Dog", py::base<Pet>() /* <- specify C++ parent type */)
206 .def(py::init<const std::string &>())
207 .def("bark", &Dog::bark);
208
209Alternatively, we can also assign a name to the previously bound ``Pet``
210:class:`class_` object and reference it when binding the ``Dog`` class:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200211
212.. code-block:: cpp
213
214 py::class_<Pet> pet(m, "Pet");
215 pet.def(py::init<const std::string &>())
216 .def_readwrite("name", &Pet::name);
217
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400218 // Method 3: pass parent class_ object:
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100219 py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200220 .def(py::init<const std::string &>())
221 .def("bark", &Dog::bark);
222
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400223Functionality-wise, all three approaches are completely equivalent. Afterwards,
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100224instances will expose fields and methods of both types:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200225
Wenzel Jakob99279f72016-06-03 11:19:29 +0200226.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200227
228 >>> p = example.Dog('Molly')
229 >>> p.name
230 u'Molly'
231 >>> p.bark()
232 u'woof!'
233
234Overloaded methods
235==================
236
237Sometimes there are several overloaded C++ methods with the same name taking
238different kinds of input arguments:
239
240.. code-block:: cpp
241
242 struct Pet {
243 Pet(const std::string &name, int age) : name(name), age(age) { }
244
245 void set(int age) { age = age; }
246 void set(const std::string &name) { name = name; }
247
248 std::string name;
249 int age;
250 };
251
252Attempting to bind ``Pet::set`` will cause an error since the compiler does not
253know which method the user intended to select. We can disambiguate by casting
254them to function pointers. Binding multiple functions to the same Python name
Wenzel Jakob0fb85282015-10-19 23:50:51 +0200255automatically creates a chain of function overloads that will be tried in
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200256sequence.
257
258.. code-block:: cpp
259
260 py::class_<Pet>(m, "Pet")
261 .def(py::init<const std::string &, int>())
262 .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
263 .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
264
265The overload signatures are also visible in the method's docstring:
266
Wenzel Jakob99279f72016-06-03 11:19:29 +0200267.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200268
269 >>> help(example.Pet)
270
271 class Pet(__builtin__.object)
272 | Methods defined here:
273 |
274 | __init__(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100275 | Signature : (Pet, str, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200276 |
277 | set(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100278 | 1. Signature : (Pet, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200279 |
280 | Set the pet's age
281 |
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100282 | 2. Signature : (Pet, str) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200283 |
284 | Set the pet's name
Wenzel Jakob93296692015-10-13 23:21:54 +0200285
286.. note::
287
288 To define multiple overloaded constructors, simply declare one after the
289 other using the ``.def(py::init<...>())`` syntax. The existing machinery
290 for specifying keyword and default arguments also works.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200291
292Enumerations and internal types
293===============================
294
Wenzel Jakob93296692015-10-13 23:21:54 +0200295Let's now suppose that the example class contains an internal enumeration type,
296e.g.:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200297
298.. code-block:: cpp
299
300 struct Pet {
301 enum Kind {
302 Dog = 0,
303 Cat
304 };
305
306 Pet(const std::string &name, Kind type) : name(name), type(type) { }
307
308 std::string name;
309 Kind type;
310 };
311
312The binding code for this example looks as follows:
313
314.. code-block:: cpp
315
316 py::class_<Pet> pet(m, "Pet");
317
318 pet.def(py::init<const std::string &, Pet::Kind>())
319 .def_readwrite("name", &Pet::name)
320 .def_readwrite("type", &Pet::type);
321
322 py::enum_<Pet::Kind>(pet, "Kind")
323 .value("Dog", Pet::Kind::Dog)
324 .value("Cat", Pet::Kind::Cat)
325 .export_values();
326
327To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
328``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
Wenzel Jakob93296692015-10-13 23:21:54 +0200329constructor. The :func:`enum_::export_values` function exports the enum entries
330into the parent scope, which should be skipped for newer C++11-style strongly
331typed enums.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200332
Wenzel Jakob99279f72016-06-03 11:19:29 +0200333.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200334
335 >>> p = Pet('Lucy', Pet.Cat)
336 >>> p.type
337 Kind.Cat
338 >>> int(p.type)
339 1L
340
341
Wenzel Jakob93296692015-10-13 23:21:54 +0200342.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.