blob: 5aad4d1bf783d189e451c467bce721e501a10635 [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
60Keyword and default arguments
61=============================
62It is possible to specify keyword and default arguments using the syntax
63discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
64and :ref:`default_args` for details.
65
66Binding lambda functions
67========================
68
69Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
70
71.. code-block:: python
72
73 >>> print(p)
74 <example.Pet object at 0x10cd98060>
75
76To address this, we could bind an utility function that returns a human-readable
77summary to the special method slot named ``__repr__``. Unfortunately, there is no
78suitable functionality in the ``Pet`` data structure, and it would be nice if
79we did not have to change it. This can easily be accomplished by binding a
80Lambda function instead:
81
82.. code-block:: cpp
83
84 py::class_<Pet>(m, "Pet")
85 .def(py::init<const std::string &>())
86 .def("setName", &Pet::setName)
87 .def("getName", &Pet::getName)
88 .def("__repr__",
89 [](const Pet &a) {
90 return "<example.Pet named '" + a.name + "'>";
91 }
92 );
93
94Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
95With the above change, the same Python code now produces the following output:
96
97.. code-block:: python
98
99 >>> print(p)
100 <example.Pet named 'Molly'>
101
102Instance and static fields
103==========================
104
105We can also directly expose the ``name`` field using the
106:func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
107method also exists for ``const`` fields.
108
109.. code-block:: cpp
110
111 py::class_<Pet>(m, "Pet")
112 .def(py::init<const std::string &>())
113 .def_readwrite("name", &Pet::name)
114 // ... remainder ...
115
116This makes it possible to write
117
118.. code-block:: python
119
120 >>> p = example.Pet('Molly')
121 >>> p.name
122 u'Molly'
123 >>> p.name = 'Charly'
124 >>> p.name
125 u'Charly'
126
127Now suppose that ``Pet::name`` was a private internal variable
128that can only be accessed via setters and getters.
129
130.. code-block:: cpp
131
132 class Pet {
133 public:
134 Pet(const std::string &name) : name(name) { }
135 void setName(const std::string &name_) { name = name_; }
136 const std::string &getName() const { return name; }
137 private:
138 std::string name;
139 };
140
141In this case, the method :func:`class_::def_property`
142(:func:`class_::def_property_readonly` for read-only data) can be used to
Wenzel Jakob93296692015-10-13 23:21:54 +0200143provide a field-like interface within Python that will transparently call
144the setter and getter functions:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200145
146.. code-block:: cpp
147
148 py::class_<Pet>(m, "Pet")
149 .def(py::init<const std::string &>())
150 .def_property("name", &Pet::getName, &Pet::setName)
151 // ... remainder ...
152
153.. seealso::
154
155 Similar functions :func:`class_::def_readwrite_static`,
156 :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
157 and :func:`class_::def_property_readonly_static` are provided for binding
158 static variables and properties.
159
Wenzel Jakob2dfbade2016-01-17 22:36:37 +0100160.. _inheritance:
161
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200162Inheritance
163===========
164
165Suppose now that the example consists of two data structures with an
166inheritance relationship:
167
168.. code-block:: cpp
169
170 struct Pet {
171 Pet(const std::string &name) : name(name) { }
172 std::string name;
173 };
174
175 struct Dog : Pet {
176 Dog(const std::string &name) : Pet(name) { }
177 std::string bark() const { return "woof!"; }
178 };
179
180To capture the hierarchical relationship in pybind11, we must assign a name to
181the ``Pet`` :class:`class_` instance and reference it when binding the ``Dog``
182class.
183
184.. code-block:: cpp
185
186 py::class_<Pet> pet(m, "Pet");
187 pet.def(py::init<const std::string &>())
188 .def_readwrite("name", &Pet::name);
189
190 py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
191 .def(py::init<const std::string &>())
192 .def("bark", &Dog::bark);
193
194Instances then expose fields and methods of both types:
195
Wenzel Jakob93296692015-10-13 23:21:54 +0200196.. code-block:: python
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200197
198 >>> p = example.Dog('Molly')
199 >>> p.name
200 u'Molly'
201 >>> p.bark()
202 u'woof!'
203
204Overloaded methods
205==================
206
207Sometimes there are several overloaded C++ methods with the same name taking
208different kinds of input arguments:
209
210.. code-block:: cpp
211
212 struct Pet {
213 Pet(const std::string &name, int age) : name(name), age(age) { }
214
215 void set(int age) { age = age; }
216 void set(const std::string &name) { name = name; }
217
218 std::string name;
219 int age;
220 };
221
222Attempting to bind ``Pet::set`` will cause an error since the compiler does not
223know which method the user intended to select. We can disambiguate by casting
224them to function pointers. Binding multiple functions to the same Python name
Wenzel Jakob0fb85282015-10-19 23:50:51 +0200225automatically creates a chain of function overloads that will be tried in
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200226sequence.
227
228.. code-block:: cpp
229
230 py::class_<Pet>(m, "Pet")
231 .def(py::init<const std::string &, int>())
232 .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
233 .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
234
235The overload signatures are also visible in the method's docstring:
236
237.. code-block:: python
238
239 >>> help(example.Pet)
240
241 class Pet(__builtin__.object)
242 | Methods defined here:
243 |
244 | __init__(...)
Wenzel Jakob6eb11da2016-01-17 22:36:36 +0100245 | Signature : (Pet, str, int) -> None
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200246 |
247 | set(...)
Wenzel Jakob6eb11da2016-01-17 22:36:36 +0100248 | 1. Signature : (Pet, int) -> None
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200249 |
250 | Set the pet's age
251 |
252 | 2. Signature : (Pet, str) -> None
253 |
254 | Set the pet's name
Wenzel Jakob93296692015-10-13 23:21:54 +0200255
256.. note::
257
258 To define multiple overloaded constructors, simply declare one after the
259 other using the ``.def(py::init<...>())`` syntax. The existing machinery
260 for specifying keyword and default arguments also works.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200261
262Enumerations and internal types
263===============================
264
Wenzel Jakob93296692015-10-13 23:21:54 +0200265Let's now suppose that the example class contains an internal enumeration type,
266e.g.:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200267
268.. code-block:: cpp
269
270 struct Pet {
271 enum Kind {
272 Dog = 0,
273 Cat
274 };
275
276 Pet(const std::string &name, Kind type) : name(name), type(type) { }
277
278 std::string name;
279 Kind type;
280 };
281
282The binding code for this example looks as follows:
283
284.. code-block:: cpp
285
286 py::class_<Pet> pet(m, "Pet");
287
288 pet.def(py::init<const std::string &, Pet::Kind>())
289 .def_readwrite("name", &Pet::name)
290 .def_readwrite("type", &Pet::type);
291
292 py::enum_<Pet::Kind>(pet, "Kind")
293 .value("Dog", Pet::Kind::Dog)
294 .value("Cat", Pet::Kind::Cat)
295 .export_values();
296
297To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
298``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
Wenzel Jakob93296692015-10-13 23:21:54 +0200299constructor. The :func:`enum_::export_values` function exports the enum entries
300into the parent scope, which should be skipped for newer C++11-style strongly
301typed enums.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200302
303.. code-block:: python
304
305 >>> p = Pet('Lucy', Pet.Cat)
306 >>> p.type
307 Kind.Cat
308 >>> int(p.type)
309 1L
310
311
Wenzel Jakob93296692015-10-13 23:21:54 +0200312.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.