blob: c98f8da2e48674b2a19c9b2eb361fbfa064e7397 [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
47.. code-block:: python
48
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
76.. code-block:: python
77
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
102.. code-block:: python
103
104 >>> print(p)
105 <example.Pet named 'Molly'>
106
107Instance 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
123.. code-block:: python
124
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
163 static variables and properties.
164
Wenzel Jakob2dfbade2016-01-17 22:36:37 +0100165.. _inheritance:
166
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200167Inheritance
168===========
169
170Suppose now that the example consists of two data structures with an
171inheritance relationship:
172
173.. code-block:: cpp
174
175 struct Pet {
176 Pet(const std::string &name) : name(name) { }
177 std::string name;
178 };
179
180 struct Dog : Pet {
181 Dog(const std::string &name) : Pet(name) { }
182 std::string bark() const { return "woof!"; }
183 };
184
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100185There are two different ways of indicating a hierarchical relationship to
186pybind11: the first is by specifying the C++ base class explicitly during
187construction using the ``base`` attribute:
188
189.. code-block:: cpp
190
191 py::class_<Pet>(m, "Pet")
192 .def(py::init<const std::string &>())
193 .def_readwrite("name", &Pet::name);
194
195 py::class_<Dog>(m, "Dog", py::base<Pet>() /* <- specify C++ parent type */)
196 .def(py::init<const std::string &>())
197 .def("bark", &Dog::bark);
198
199Alternatively, we can also assign a name to the previously bound ``Pet``
200:class:`class_` object and reference it when binding the ``Dog`` class:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200201
202.. code-block:: cpp
203
204 py::class_<Pet> pet(m, "Pet");
205 pet.def(py::init<const std::string &>())
206 .def_readwrite("name", &Pet::name);
207
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100208 py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200209 .def(py::init<const std::string &>())
210 .def("bark", &Dog::bark);
211
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100212Functionality-wise, both approaches are completely equivalent. Afterwards,
213instances will expose fields and methods of both types:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200214
Wenzel Jakob93296692015-10-13 23:21:54 +0200215.. code-block:: python
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200216
217 >>> p = example.Dog('Molly')
218 >>> p.name
219 u'Molly'
220 >>> p.bark()
221 u'woof!'
222
223Overloaded methods
224==================
225
226Sometimes there are several overloaded C++ methods with the same name taking
227different kinds of input arguments:
228
229.. code-block:: cpp
230
231 struct Pet {
232 Pet(const std::string &name, int age) : name(name), age(age) { }
233
234 void set(int age) { age = age; }
235 void set(const std::string &name) { name = name; }
236
237 std::string name;
238 int age;
239 };
240
241Attempting to bind ``Pet::set`` will cause an error since the compiler does not
242know which method the user intended to select. We can disambiguate by casting
243them to function pointers. Binding multiple functions to the same Python name
Wenzel Jakob0fb85282015-10-19 23:50:51 +0200244automatically creates a chain of function overloads that will be tried in
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200245sequence.
246
247.. code-block:: cpp
248
249 py::class_<Pet>(m, "Pet")
250 .def(py::init<const std::string &, int>())
251 .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
252 .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
253
254The overload signatures are also visible in the method's docstring:
255
256.. code-block:: python
257
258 >>> help(example.Pet)
259
260 class Pet(__builtin__.object)
261 | Methods defined here:
262 |
263 | __init__(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100264 | Signature : (Pet, str, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200265 |
266 | set(...)
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100267 | 1. Signature : (Pet, int) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200268 |
269 | Set the pet's age
270 |
Wenzel Jakob48548ea2016-01-17 22:36:44 +0100271 | 2. Signature : (Pet, str) -> NoneType
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200272 |
273 | Set the pet's name
Wenzel Jakob93296692015-10-13 23:21:54 +0200274
275.. note::
276
277 To define multiple overloaded constructors, simply declare one after the
278 other using the ``.def(py::init<...>())`` syntax. The existing machinery
279 for specifying keyword and default arguments also works.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200280
281Enumerations and internal types
282===============================
283
Wenzel Jakob93296692015-10-13 23:21:54 +0200284Let's now suppose that the example class contains an internal enumeration type,
285e.g.:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200286
287.. code-block:: cpp
288
289 struct Pet {
290 enum Kind {
291 Dog = 0,
292 Cat
293 };
294
295 Pet(const std::string &name, Kind type) : name(name), type(type) { }
296
297 std::string name;
298 Kind type;
299 };
300
301The binding code for this example looks as follows:
302
303.. code-block:: cpp
304
305 py::class_<Pet> pet(m, "Pet");
306
307 pet.def(py::init<const std::string &, Pet::Kind>())
308 .def_readwrite("name", &Pet::name)
309 .def_readwrite("type", &Pet::type);
310
311 py::enum_<Pet::Kind>(pet, "Kind")
312 .value("Dog", Pet::Kind::Dog)
313 .value("Cat", Pet::Kind::Cat)
314 .export_values();
315
316To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
317``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
Wenzel Jakob93296692015-10-13 23:21:54 +0200318constructor. The :func:`enum_::export_values` function exports the enum entries
319into the parent scope, which should be skipped for newer C++11-style strongly
320typed enums.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200321
322.. code-block:: python
323
324 >>> p = Pet('Lucy', Pet.Cat)
325 >>> p.type
326 Kind.Cat
327 >>> int(p.type)
328 1L
329
330
Wenzel Jakob93296692015-10-13 23:21:54 +0200331.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.