blob: 300816d41cd7548cf43063a998f37ff73e668ef6 [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
Dean Moldovan9273af42016-10-13 23:53:16 +0200168Dynamic attributes
169==================
170
171Native Python classes can pick up new attributes dynamically:
172
173.. code-block:: pycon
174
175 >>> class Pet:
176 ... name = 'Molly'
177 ...
178 >>> p = Pet()
179 >>> p.name = 'Charly' # overwrite existing
180 >>> p.age = 2 # dynamically add a new attribute
181
182By default, classes exported from C++ do not support this and the only writable
183attributes are the ones explicitly defined using :func:`class_::def_readwrite`
184or :func:`class_::def_property`.
185
186.. code-block:: cpp
187
188 py::class_<Pet>(m, "Pet")
189 .def(py::init<>())
190 .def_readwrite("name", &Pet::name);
191
192Trying to set any other attribute results in an error:
193
194.. code-block:: pycon
195
196 >>> p = example.Pet()
197 >>> p.name = 'Charly' # OK, attribute defined in C++
198 >>> p.age = 2 # fail
199 AttributeError: 'Pet' object has no attribute 'age'
200
201To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
202must be added to the :class:`py::class_` constructor:
203
204.. code-block:: cpp
205
206 py::class_<Pet>(m, "Pet", py::dynamic_attr())
207 .def(py::init<>())
208 .def_readwrite("name", &Pet::name);
209
210Now everything works as expected:
211
212.. code-block:: pycon
213
214 >>> p = example.Pet()
215 >>> p.name = 'Charly' # OK, overwrite value in C++
216 >>> p.age = 2 # OK, dynamically add a new attribute
217 >>> p.__dict__ # just like a native Python class
218 {'age': 2}
219
220Note that there is a small runtime cost for a class with dynamic attributes.
221Not only because of the addition of a ``__dict__``, but also because of more
222expensive garbage collection tracking which must be activated to resolve
223possible circular references. Native Python classes incur this same cost by
224default, so this is not anything to worry about. By default, pybind11 classes
225are more efficient than native Python classes. Enabling dynamic attributes
226just brings them on par.
227
Wenzel Jakob2dfbade2016-01-17 22:36:37 +0100228.. _inheritance:
229
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200230Inheritance
231===========
232
233Suppose now that the example consists of two data structures with an
234inheritance relationship:
235
236.. code-block:: cpp
237
238 struct Pet {
239 Pet(const std::string &name) : name(name) { }
240 std::string name;
241 };
242
243 struct Dog : Pet {
244 Dog(const std::string &name) : Pet(name) { }
245 std::string bark() const { return "woof!"; }
246 };
247
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900248There are two different ways of indicating a hierarchical relationship to
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400249pybind11: the first specifies the C++ base class as an extra template
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900250parameter of the :class:`class_`:
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100251
252.. code-block:: cpp
253
254 py::class_<Pet>(m, "Pet")
255 .def(py::init<const std::string &>())
256 .def_readwrite("name", &Pet::name);
257
Jason Rhinelander6b52c832016-09-06 12:27:00 -0400258 // Method 1: template parameter:
259 py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
260 .def(py::init<const std::string &>())
261 .def("bark", &Dog::bark);
262
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100263Alternatively, we can also assign a name to the previously bound ``Pet``
264:class:`class_` object and reference it when binding the ``Dog`` class:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200265
266.. code-block:: cpp
267
268 py::class_<Pet> pet(m, "Pet");
269 pet.def(py::init<const std::string &>())
270 .def_readwrite("name", &Pet::name);
271
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900272 // Method 2: pass parent class_ object:
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100273 py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200274 .def(py::init<const std::string &>())
275 .def("bark", &Dog::bark);
276
Wenzel Jakobbad589a2016-09-12 12:03:20 +0900277Functionality-wise, both approaches are equivalent. Afterwards, instances will
278expose fields and methods of both types:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200279
Wenzel Jakob99279f72016-06-03 11:19:29 +0200280.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200281
282 >>> p = example.Dog('Molly')
283 >>> p.name
284 u'Molly'
285 >>> p.bark()
286 u'woof!'
287
288Overloaded methods
289==================
290
291Sometimes there are several overloaded C++ methods with the same name taking
292different kinds of input arguments:
293
294.. code-block:: cpp
295
296 struct Pet {
297 Pet(const std::string &name, int age) : name(name), age(age) { }
298
299 void set(int age) { age = age; }
300 void set(const std::string &name) { name = name; }
301
302 std::string name;
303 int age;
304 };
305
306Attempting to bind ``Pet::set`` will cause an error since the compiler does not
307know which method the user intended to select. We can disambiguate by casting
308them to function pointers. Binding multiple functions to the same Python name
Wenzel Jakob0fb85282015-10-19 23:50:51 +0200309automatically creates a chain of function overloads that will be tried in
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200310sequence.
311
312.. code-block:: cpp
313
314 py::class_<Pet>(m, "Pet")
315 .def(py::init<const std::string &, int>())
316 .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
317 .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
318
319The overload signatures are also visible in the method's docstring:
320
Wenzel Jakob99279f72016-06-03 11:19:29 +0200321.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200322
323 >>> help(example.Pet)
324
325 class Pet(__builtin__.object)
326 | Methods defined here:
327 |
328 | __init__(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100329 | Signature : (Pet, str, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200330 |
331 | set(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100332 | 1. Signature : (Pet, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200333 |
334 | Set the pet's age
335 |
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100336 | 2. Signature : (Pet, str) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200337 |
338 | Set the pet's name
Wenzel Jakob93296692015-10-13 23:21:54 +0200339
340.. note::
341
342 To define multiple overloaded constructors, simply declare one after the
343 other using the ``.def(py::init<...>())`` syntax. The existing machinery
344 for specifying keyword and default arguments also works.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200345
346Enumerations and internal types
347===============================
348
Wenzel Jakob93296692015-10-13 23:21:54 +0200349Let's now suppose that the example class contains an internal enumeration type,
350e.g.:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200351
352.. code-block:: cpp
353
354 struct Pet {
355 enum Kind {
356 Dog = 0,
357 Cat
358 };
359
360 Pet(const std::string &name, Kind type) : name(name), type(type) { }
361
362 std::string name;
363 Kind type;
364 };
365
366The binding code for this example looks as follows:
367
368.. code-block:: cpp
369
370 py::class_<Pet> pet(m, "Pet");
371
372 pet.def(py::init<const std::string &, Pet::Kind>())
373 .def_readwrite("name", &Pet::name)
374 .def_readwrite("type", &Pet::type);
375
376 py::enum_<Pet::Kind>(pet, "Kind")
377 .value("Dog", Pet::Kind::Dog)
378 .value("Cat", Pet::Kind::Cat)
379 .export_values();
380
381To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
382``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
Wenzel Jakob93296692015-10-13 23:21:54 +0200383constructor. The :func:`enum_::export_values` function exports the enum entries
384into the parent scope, which should be skipped for newer C++11-style strongly
385typed enums.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200386
Wenzel Jakob99279f72016-06-03 11:19:29 +0200387.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200388
389 >>> p = Pet('Lucy', Pet.Cat)
390 >>> p.type
391 Kind.Cat
392 >>> int(p.type)
393 1L
394
395
Wenzel Jakob93296692015-10-13 23:21:54 +0200396.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.