classes.rst 16.1 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_MODULE(example, m) {
31
32
33
34
35
36
        py::class_<Pet>(m, "Pet")
            .def(py::init<const std::string &>())
            .def("setName", &Pet::setName)
            .def("getName", &Pet::getName);
    }

37
:class:`class_` creates bindings for a C++ *class* or *struct*-style data
38
39
40
41
42
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:

43
.. code-block:: pycon
44
45
46

    % python
    >>> import example
47
    >>> p = example.Pet("Molly")
48
49
50
51
    >>> print(p)
    <example.Pet object at 0x10cd98060>
    >>> p.getName()
    u'Molly'
52
    >>> p.setName("Charly")
53
54
55
    >>> p.getName()
    u'Charly'

56
57
58
59
60
.. seealso::

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

61
62
63
64
65
66
67
68
69
70
71
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:

72
.. code-block:: pycon
73
74
75
76

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

Mosalam Ebrahimi's avatar
Mosalam Ebrahimi committed
77
To address this, we could bind a utility function that returns a human-readable
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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:

98
.. code-block:: pycon
99
100
101
102

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

103
104
.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.

105
106
.. _properties:

107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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

123
.. code-block:: pycon
124

125
    >>> p = example.Pet("Molly")
126
127
    >>> p.name
    u'Molly'
128
    >>> p.name = "Charly"
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    >>> 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
148
149
provide a field-like interface within Python that will transparently call
the setter and getter functions:
150
151
152
153
154
155
156
157

.. code-block:: cpp

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

158
159
160
Write only properties can be defined by passing ``nullptr`` as the
input for the read function.

161
162
163
164
165
.. 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
166
167
    static variables and properties. Please also see the section on
    :ref:`static_properties` in the advanced part of the documentation.
168

Dean Moldovan's avatar
Dean Moldovan committed
169
170
171
172
173
174
175
176
Dynamic attributes
==================

Native Python classes can pick up new attributes dynamically:

.. code-block:: pycon

    >>> class Pet:
177
    ...     name = "Molly"
Dean Moldovan's avatar
Dean Moldovan committed
178
179
    ...
    >>> p = Pet()
180
    >>> p.name = "Charly"  # overwrite existing
Dean Moldovan's avatar
Dean Moldovan committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
    >>> p.age = 2  # dynamically add a new attribute

By default, classes exported from C++ do not support this and the only writable
attributes are the ones explicitly defined using :func:`class_::def_readwrite`
or :func:`class_::def_property`.

.. code-block:: cpp

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

Trying to set any other attribute results in an error:

.. code-block:: pycon

    >>> p = example.Pet()
198
    >>> p.name = "Charly"  # OK, attribute defined in C++
Dean Moldovan's avatar
Dean Moldovan committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
    >>> p.age = 2  # fail
    AttributeError: 'Pet' object has no attribute 'age'

To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
must be added to the :class:`py::class_` constructor:

.. code-block:: cpp

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

Now everything works as expected:

.. code-block:: pycon

    >>> p = example.Pet()
216
    >>> p.name = "Charly"  # OK, overwrite value in C++
Dean Moldovan's avatar
Dean Moldovan committed
217
218
219
220
221
222
223
224
225
226
227
228
    >>> p.age = 2  # OK, dynamically add a new attribute
    >>> p.__dict__  # just like a native Python class
    {'age': 2}

Note that there is a small runtime cost for a class with dynamic attributes.
Not only because of the addition of a ``__dict__``, but also because of more
expensive garbage collection tracking which must be activated to resolve
possible circular references. Native Python classes incur this same cost by
default, so this is not anything to worry about. By default, pybind11 classes
are more efficient than native Python classes. Enabling dynamic attributes
just brings them on par.

229
230
.. _inheritance:

231
232
Inheritance and automatic downcasting
=====================================
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248

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!"; }
    };

249
There are two different ways of indicating a hierarchical relationship to
250
pybind11: the first specifies the C++ base class as an extra template
251
parameter of the :class:`class_`:
Wenzel Jakob's avatar
Wenzel Jakob committed
252
253
254
255
256
257
258

.. code-block:: cpp

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

259
260
261
262
263
    // Method 1: template parameter:
    py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
        .def(py::init<const std::string &>())
        .def("bark", &Dog::bark);

Wenzel Jakob's avatar
Wenzel Jakob committed
264
265
Alternatively, we can also assign a name to the previously bound ``Pet``
:class:`class_` object and reference it when binding the ``Dog`` class:
266
267
268
269
270
271
272

.. code-block:: cpp

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

273
    // Method 2: pass parent class_ object:
Wenzel Jakob's avatar
Wenzel Jakob committed
274
    py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
275
276
277
        .def(py::init<const std::string &>())
        .def("bark", &Dog::bark);

278
279
Functionality-wise, both approaches are equivalent. Afterwards, instances will
expose fields and methods of both types:
280

281
.. code-block:: pycon
282

283
    >>> p = example.Dog("Molly")
284
285
286
287
288
    >>> p.name
    u'Molly'
    >>> p.bark()
    u'woof!'

289
290
291
292
293
294
295
296
297
298
299
300
The C++ classes defined above are regular non-polymorphic types with an
inheritance relationship. This is reflected in Python:

.. code-block:: cpp

    // Return a base pointer to a derived instance
    m.def("pet_store", []() { return std::unique_ptr<Pet>(new Dog("Molly")); });

.. code-block:: pycon

    >>> p = example.pet_store()
    >>> type(p)  # `Dog` instance behind `Pet` pointer
301
    Pet          # no pointer downcasting for regular non-polymorphic types
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
    >>> p.bark()
    AttributeError: 'Pet' object has no attribute 'bark'

The function returned a ``Dog`` instance, but because it's a non-polymorphic
type behind a base pointer, Python only sees a ``Pet``. In C++, a type is only
considered polymorphic if it has at least one virtual function and pybind11
will automatically recognize this:

.. code-block:: cpp

    struct PolymorphicPet {
        virtual ~PolymorphicPet() = default;
    };

    struct PolymorphicDog : PolymorphicPet {
        std::string bark() const { return "woof!"; }
    };

    // Same binding code
    py::class_<PolymorphicPet>(m, "PolymorphicPet");
    py::class_<PolymorphicDog, PolymorphicPet>(m, "PolymorphicDog")
        .def(py::init<>())
        .def("bark", &PolymorphicDog::bark);

    // Again, return a base pointer to a derived instance
    m.def("pet_store2", []() { return std::unique_ptr<PolymorphicPet>(new PolymorphicDog); });

.. code-block:: pycon

    >>> p = example.pet_store2()
    >>> type(p)
333
    PolymorphicDog  # automatically downcast
334
335
336
    >>> p.bark()
    u'woof!'

337
Given a pointer to a polymorphic base, pybind11 performs automatic downcasting
338
339
340
341
342
343
344
345
346
347
to the actual derived type. Note that this goes beyond the usual situation in
C++: we don't just get access to the virtual functions of the base, we get the
concrete derived type including functions and attributes that the base type may
not even be aware of.

.. seealso::

    For more information about polymorphic behavior see :ref:`overriding_virtuals`.


348
349
350
351
352
353
354
355
356
357
358
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) { }

359
360
        void set(int age_) { age = age_; }
        void set(const std::string &name_) { name = name_; }
361
362
363
364
365
366
367
368

        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
369
automatically creates a chain of function overloads that will be tried in
370
371
372
373
374
375
sequence.

.. code-block:: cpp

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

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

381
.. code-block:: pycon
382
383
384
385
386
387
388

    >>> help(example.Pet)

    class Pet(__builtin__.object)
     |  Methods defined here:
     |
     |  __init__(...)
Wenzel Jakob's avatar
Wenzel Jakob committed
389
     |      Signature : (Pet, str, int) -> NoneType
390
391
     |
     |  set(...)
Wenzel Jakob's avatar
Wenzel Jakob committed
392
     |      1. Signature : (Pet, int) -> NoneType
393
394
395
     |
     |      Set the pet's age
     |
Wenzel Jakob's avatar
Wenzel Jakob committed
396
     |      2. Signature : (Pet, str) -> NoneType
397
398
     |
     |      Set the pet's name
Wenzel Jakob's avatar
Wenzel Jakob committed
399

400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
syntax to cast the overloaded function:

.. code-block:: cpp

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

Here, ``py::overload_cast`` only requires the parameter types to be specified.
The return type and class are deduced. This avoids the additional noise of
``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
on constness, the ``py::const_`` tag should be used:

.. code-block:: cpp

    struct Widget {
        int foo(int x, float y);
        int foo(int x, float y) const;
    };

    py::class_<Widget>(m, "Widget")
       .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
       .def("foo_const",   py::overload_cast<int, float>(&Widget::foo, py::const_));

425
426
427
428
429
430
431
432
433
434
435
If you prefer the ``py::overload_cast`` syntax but have a C++11 compatible compiler only,
you can use ``py::detail::overload_cast_impl`` with an additional set of parentheses:

.. code-block:: cpp

    template <typename... Args>
    using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;

    py::class_<Pet>(m, "Pet")
        .def("set", overload_cast_<int>()(&Pet::set), "Set the pet's age")
        .def("set", overload_cast_<const std::string &>()(&Pet::set), "Set the pet's name");
436
437
438
439

.. [#cpp14] A compiler which supports the ``-std=c++14`` flag
            or Visual Studio 2015 Update 2 and newer.

Wenzel Jakob's avatar
Wenzel Jakob committed
440
441
442
443
444
.. 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.
445
446
447
448

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

449
Let's now suppose that the example class contains internal types like enumerations, e.g.:
450
451
452
453
454
455
456
457
458

.. code-block:: cpp

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

459
460
461
462
        struct Attributes {
            float age = 0;
        };

463
464
465
466
        Pet(const std::string &name, Kind type) : name(name), type(type) { }

        std::string name;
        Kind type;
467
        Attributes attr;
468
469
470
471
472
473
474
475
476
477
    };

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)
478
479
        .def_readwrite("type", &Pet::type)
        .def_readwrite("attr", &Pet::attr);
480
481
482
483
484
485

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

486
487
488
489
490
491
492
    py::class_<Pet::Attributes> attributes(pet, "Attributes")
        .def(py::init<>())
        .def_readwrite("age", &Pet::Attributes::age);


To ensure that the nested types ``Kind`` and ``Attributes`` are created within the scope of ``Pet``, the
``pet`` :class:`class_` instance must be supplied to the :class:`enum_` and :class:`class_`
Wenzel Jakob's avatar
Wenzel Jakob committed
493
494
495
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.
496

497
.. code-block:: pycon
498

499
    >>> p = Pet("Lucy", Pet.Cat)
500
501
502
503
504
    >>> p.type
    Kind.Cat
    >>> int(p.type)
    1L

505
506
507
508
509
510
The entries defined by the enumeration type are exposed in the ``__members__`` property:

.. code-block:: pycon

    >>> Pet.Kind.__members__
    {'Dog': Kind.Dog, 'Cat': Kind.Cat}
511

512
513
514
515
516
517
518
519
520
The ``name`` property returns the name of the enum value as a unicode string.

.. note::

    It is also possible to use ``str(enum)``, however these accomplish different
    goals. The following shows how these two approaches differ.

    .. code-block:: pycon

521
        >>> p = Pet("Lucy", Pet.Cat)
522
523
524
525
526
527
528
529
        >>> pet_type = p.type
        >>> pet_type
        Pet.Cat
        >>> str(pet_type)
        'Pet.Cat'
        >>> pet_type.name
        'Cat'

530
531
532
533
534
535
536
537
538
539
540
541
542
.. note::

    When the special tag ``py::arithmetic()`` is specified to the ``enum_``
    constructor, pybind11 creates an enumeration that also supports rudimentary
    arithmetic and bit-level operations like comparisons, and, or, xor, negation,
    etc.

    .. code-block:: cpp

        py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
           ...

    By default, these are omitted to conserve space.