blob: a7c75d83838a472b62becbab01430cb1aa6bd197 [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 Jakob93296692015-10-13 23:21:54 +020030 PYBIND_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
160Inheritance
161===========
162
163Suppose now that the example consists of two data structures with an
164inheritance relationship:
165
166.. code-block:: cpp
167
168 struct Pet {
169 Pet(const std::string &name) : name(name) { }
170 std::string name;
171 };
172
173 struct Dog : Pet {
174 Dog(const std::string &name) : Pet(name) { }
175 std::string bark() const { return "woof!"; }
176 };
177
178To capture the hierarchical relationship in pybind11, we must assign a name to
179the ``Pet`` :class:`class_` instance and reference it when binding the ``Dog``
180class.
181
182.. code-block:: cpp
183
184 py::class_<Pet> pet(m, "Pet");
185 pet.def(py::init<const std::string &>())
186 .def_readwrite("name", &Pet::name);
187
188 py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
189 .def(py::init<const std::string &>())
190 .def("bark", &Dog::bark);
191
192Instances then expose fields and methods of both types:
193
Wenzel Jakob93296692015-10-13 23:21:54 +0200194.. code-block:: python
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200195
196 >>> p = example.Dog('Molly')
197 >>> p.name
198 u'Molly'
199 >>> p.bark()
200 u'woof!'
201
202Overloaded methods
203==================
204
205Sometimes there are several overloaded C++ methods with the same name taking
206different kinds of input arguments:
207
208.. code-block:: cpp
209
210 struct Pet {
211 Pet(const std::string &name, int age) : name(name), age(age) { }
212
213 void set(int age) { age = age; }
214 void set(const std::string &name) { name = name; }
215
216 std::string name;
217 int age;
218 };
219
220Attempting to bind ``Pet::set`` will cause an error since the compiler does not
221know which method the user intended to select. We can disambiguate by casting
222them to function pointers. Binding multiple functions to the same Python name
223automatically creates a chain of fucnction overloads that will be tried in
224sequence.
225
226.. code-block:: cpp
227
228 py::class_<Pet>(m, "Pet")
229 .def(py::init<const std::string &, int>())
230 .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
231 .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
232
233The overload signatures are also visible in the method's docstring:
234
235.. code-block:: python
236
237 >>> help(example.Pet)
238
239 class Pet(__builtin__.object)
240 | Methods defined here:
241 |
242 | __init__(...)
243 | Signature : (Pet, str, int32_t) -> None
244 |
245 | set(...)
246 | 1. Signature : (Pet, int32_t) -> None
247 |
248 | Set the pet's age
249 |
250 | 2. Signature : (Pet, str) -> None
251 |
252 | Set the pet's name
Wenzel Jakob93296692015-10-13 23:21:54 +0200253
254.. note::
255
256 To define multiple overloaded constructors, simply declare one after the
257 other using the ``.def(py::init<...>())`` syntax. The existing machinery
258 for specifying keyword and default arguments also works.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200259
260Enumerations and internal types
261===============================
262
Wenzel Jakob93296692015-10-13 23:21:54 +0200263Let's now suppose that the example class contains an internal enumeration type,
264e.g.:
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200265
266.. code-block:: cpp
267
268 struct Pet {
269 enum Kind {
270 Dog = 0,
271 Cat
272 };
273
274 Pet(const std::string &name, Kind type) : name(name), type(type) { }
275
276 std::string name;
277 Kind type;
278 };
279
280The binding code for this example looks as follows:
281
282.. code-block:: cpp
283
284 py::class_<Pet> pet(m, "Pet");
285
286 pet.def(py::init<const std::string &, Pet::Kind>())
287 .def_readwrite("name", &Pet::name)
288 .def_readwrite("type", &Pet::type);
289
290 py::enum_<Pet::Kind>(pet, "Kind")
291 .value("Dog", Pet::Kind::Dog)
292 .value("Cat", Pet::Kind::Cat)
293 .export_values();
294
295To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
296``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
Wenzel Jakob93296692015-10-13 23:21:54 +0200297constructor. The :func:`enum_::export_values` function exports the enum entries
298into the parent scope, which should be skipped for newer C++11-style strongly
299typed enums.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200300
301.. code-block:: python
302
303 >>> p = Pet('Lucy', Pet.Cat)
304 >>> p.type
305 Kind.Cat
306 >>> int(p.type)
307 1L
308
309
Wenzel Jakob93296692015-10-13 23:21:54 +0200310.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.