classes.rst 9.28 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
.. _classes:

Object-oriented code
####################

Creating bindings for a custom type
===================================

Let's now look at a more complex example where we'll create bindings for a
custom C++ data structure named ``Pet``. Its definition is given below:

.. code-block:: cpp

    struct Pet {
        Pet(const std::string &name) : name(name) { }
        void setName(const std::string &name_) { name = name_; }
        const std::string &getName() const { return name; }

        std::string name;
    };

The binding code for ``Pet`` looks as follows:

.. code-block:: cpp

26
    #include <pybind11/pybind11.h>
Wenzel Jakob's avatar
Wenzel Jakob committed
27

28
    namespace py = pybind11;
29

30
    PYBIND11_PLUGIN(example) {
31
        py::module m("example", "pybind11 example plugin");
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

        py::class_<Pet>(m, "Pet")
            .def(py::init<const std::string &>())
            .def("setName", &Pet::setName)
            .def("getName", &Pet::getName);

        return m.ptr();
    }

:class:`class_` creates bindings for a C++ `class` or `struct`-style data
structure. :func:`init` is a convenience function that takes the types of a
constructor's parameters as template arguments and wraps the corresponding
constructor (see the :ref:`custom_constructors` section for details). An
interactive Python session demonstrating this example is shown below:

47
.. code-block:: pycon
48
49
50
51
52
53
54
55
56
57
58
59

    % python
    >>> import example
    >>> p = example.Pet('Molly')
    >>> print(p)
    <example.Pet object at 0x10cd98060>
    >>> p.getName()
    u'Molly'
    >>> p.setName('Charly')
    >>> p.getName()
    u'Charly'

60
61
62
63
64
.. seealso::

    Static member functions can be bound in the same way using
    :func:`class_::def_static`.

65
66
67
68
69
70
71
72
73
74
75
Keyword and default arguments
=============================
It is possible to specify keyword and default arguments using the syntax
discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
and :ref:`default_args` for details.

Binding lambda functions
========================

Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:

76
.. code-block:: pycon
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

    >>> print(p)
    <example.Pet object at 0x10cd98060>

To address this, we could bind an utility function that returns a human-readable
summary to the special method slot named ``__repr__``. Unfortunately, there is no
suitable functionality in the ``Pet`` data structure, and it would be nice if
we did not have to change it. This can easily be accomplished by binding a
Lambda function instead:

.. code-block:: cpp

        py::class_<Pet>(m, "Pet")
            .def(py::init<const std::string &>())
            .def("setName", &Pet::setName)
            .def("getName", &Pet::getName)
            .def("__repr__",
                [](const Pet &a) {
                    return "<example.Pet named '" + a.name + "'>";
                }
            );

Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
With the above change, the same Python code now produces the following output:

102
.. code-block:: pycon
103
104
105
106

    >>> print(p)
    <example.Pet named 'Molly'>

107
108
.. _properties:

109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
Instance and static fields
==========================

We can also directly expose the ``name`` field using the
:func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
method also exists for ``const`` fields.

.. code-block:: cpp

        py::class_<Pet>(m, "Pet")
            .def(py::init<const std::string &>())
            .def_readwrite("name", &Pet::name)
            // ... remainder ...

This makes it possible to write

125
.. code-block:: pycon
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149

    >>> p = example.Pet('Molly')
    >>> p.name
    u'Molly'
    >>> p.name = 'Charly'
    >>> p.name
    u'Charly'

Now suppose that ``Pet::name`` was a private internal variable
that can only be accessed via setters and getters.

.. code-block:: cpp

    class Pet {
    public:
        Pet(const std::string &name) : name(name) { }
        void setName(const std::string &name_) { name = name_; }
        const std::string &getName() const { return name; }
    private:
        std::string name;
    };

In this case, the method :func:`class_::def_property`
(:func:`class_::def_property_readonly` for read-only data) can be used to
Wenzel Jakob's avatar
Wenzel Jakob committed
150
151
provide a field-like interface within Python that will transparently call
the setter and getter functions:
152
153
154
155
156
157
158
159
160
161
162
163
164

.. code-block:: cpp

        py::class_<Pet>(m, "Pet")
            .def(py::init<const std::string &>())
            .def_property("name", &Pet::getName, &Pet::setName)
            // ... remainder ...

.. seealso::

    Similar functions :func:`class_::def_readwrite_static`,
    :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
    and :func:`class_::def_property_readonly_static` are provided for binding
165
166
    static variables and properties. Please also see the section on
    :ref:`static_properties` in the advanced part of the documentation.
167

168
169
.. _inheritance:

170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
Inheritance
===========

Suppose now that the example consists of two data structures with an
inheritance relationship:

.. code-block:: cpp

    struct Pet {
        Pet(const std::string &name) : name(name) { }
        std::string name;
    };

    struct Dog : Pet {
        Dog(const std::string &name) : Pet(name) { }
        std::string bark() const { return "woof!"; }
    };

Wenzel Jakob's avatar
Wenzel Jakob committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
There are two different ways of indicating a hierarchical relationship to
pybind11: the first is by specifying the C++ base class explicitly during
construction using the ``base`` attribute:

.. code-block:: cpp

    py::class_<Pet>(m, "Pet")
       .def(py::init<const std::string &>())
       .def_readwrite("name", &Pet::name);

    py::class_<Dog>(m, "Dog", py::base<Pet>() /* <- specify C++ parent type */)
        .def(py::init<const std::string &>())
        .def("bark", &Dog::bark);

Alternatively, we can also assign a name to the previously bound ``Pet``
:class:`class_` object and reference it when binding the ``Dog`` class:
204
205
206
207
208
209
210

.. code-block:: cpp

    py::class_<Pet> pet(m, "Pet");
    pet.def(py::init<const std::string &>())
       .def_readwrite("name", &Pet::name);

Wenzel Jakob's avatar
Wenzel Jakob committed
211
    py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
212
213
214
        .def(py::init<const std::string &>())
        .def("bark", &Dog::bark);

Wenzel Jakob's avatar
Wenzel Jakob committed
215
216
Functionality-wise, both approaches are completely equivalent. Afterwards,
instances will expose fields and methods of both types:
217

218
.. code-block:: pycon
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246

    >>> p = example.Dog('Molly')
    >>> p.name
    u'Molly'
    >>> p.bark()
    u'woof!'

Overloaded methods
==================

Sometimes there are several overloaded C++ methods with the same name taking
different kinds of input arguments:

.. code-block:: cpp

    struct Pet {
        Pet(const std::string &name, int age) : name(name), age(age) { }

        void set(int age) { age = age; }
        void set(const std::string &name) { name = name; }

        std::string name;
        int age;
    };

Attempting to bind ``Pet::set`` will cause an error since the compiler does not
know which method the user intended to select. We can disambiguate by casting
them to function pointers. Binding multiple functions to the same Python name
247
automatically creates a chain of function overloads that will be tried in
248
249
250
251
252
253
254
255
256
257
258
sequence.

.. code-block:: cpp

    py::class_<Pet>(m, "Pet")
       .def(py::init<const std::string &, int>())
       .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
       .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");

The overload signatures are also visible in the method's docstring:

259
.. code-block:: pycon
260
261
262
263
264
265
266

    >>> help(example.Pet)

    class Pet(__builtin__.object)
     |  Methods defined here:
     |
     |  __init__(...)
Wenzel Jakob's avatar
Wenzel Jakob committed
267
     |      Signature : (Pet, str, int) -> NoneType
268
269
     |
     |  set(...)
Wenzel Jakob's avatar
Wenzel Jakob committed
270
     |      1. Signature : (Pet, int) -> NoneType
271
272
273
     |
     |      Set the pet's age
     |
Wenzel Jakob's avatar
Wenzel Jakob committed
274
     |      2. Signature : (Pet, str) -> NoneType
275
276
     |
     |      Set the pet's name
Wenzel Jakob's avatar
Wenzel Jakob committed
277
278
279
280
281
282

.. note::

    To define multiple overloaded constructors, simply declare one after the
    other using the ``.def(py::init<...>())`` syntax. The existing machinery
    for specifying keyword and default arguments also works.
283
284
285
286

Enumerations and internal types
===============================

Wenzel Jakob's avatar
Wenzel Jakob committed
287
288
Let's now suppose that the example class contains an internal enumeration type,
e.g.:
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320

.. code-block:: cpp

    struct Pet {
        enum Kind {
            Dog = 0,
            Cat
        };

        Pet(const std::string &name, Kind type) : name(name), type(type) { }

        std::string name;
        Kind type;
    };

The binding code for this example looks as follows:

.. code-block:: cpp

    py::class_<Pet> pet(m, "Pet");

    pet.def(py::init<const std::string &, Pet::Kind>())
        .def_readwrite("name", &Pet::name)
        .def_readwrite("type", &Pet::type);

    py::enum_<Pet::Kind>(pet, "Kind")
        .value("Dog", Pet::Kind::Dog)
        .value("Cat", Pet::Kind::Cat)
        .export_values();

To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
Wenzel Jakob's avatar
Wenzel Jakob committed
321
322
323
constructor. The :func:`enum_::export_values` function exports the enum entries
into the parent scope, which should be skipped for newer C++11-style strongly
typed enums.
324

325
.. code-block:: pycon
326
327
328
329
330
331
332
333

    >>> p = Pet('Lucy', Pet.Cat)
    >>> p.type
    Kind.Cat
    >>> int(p.type)
    1L


Wenzel Jakob's avatar
Wenzel Jakob committed
334
.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.