classes.rst revision 11986:c12e4625ab56
1.. _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
26    #include <pybind11/pybind11.h>
27
28    namespace py = pybind11;
29
30    PYBIND11_PLUGIN(example) {
31        py::module m("example", "pybind11 example plugin");
32
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:: pycon
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
60.. seealso::
61
62    Static member functions can be bound in the same way using
63    :func:`class_::def_static`.
64
65Keyword 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:: pycon
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:: pycon
103
104    >>> print(p)
105    <example.Pet named 'Molly'>
106
107.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.
108
109.. _properties:
110
111Instance and static fields
112==========================
113
114We can also directly expose the ``name`` field using the
115:func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
116method also exists for ``const`` fields.
117
118.. code-block:: cpp
119
120        py::class_<Pet>(m, "Pet")
121            .def(py::init<const std::string &>())
122            .def_readwrite("name", &Pet::name)
123            // ... remainder ...
124
125This makes it possible to write
126
127.. code-block:: pycon
128
129    >>> p = example.Pet('Molly')
130    >>> p.name
131    u'Molly'
132    >>> p.name = 'Charly'
133    >>> p.name
134    u'Charly'
135
136Now suppose that ``Pet::name`` was a private internal variable
137that can only be accessed via setters and getters.
138
139.. code-block:: cpp
140
141    class Pet {
142    public:
143        Pet(const std::string &name) : name(name) { }
144        void setName(const std::string &name_) { name = name_; }
145        const std::string &getName() const { return name; }
146    private:
147        std::string name;
148    };
149
150In this case, the method :func:`class_::def_property`
151(:func:`class_::def_property_readonly` for read-only data) can be used to
152provide a field-like interface within Python that will transparently call
153the setter and getter functions:
154
155.. code-block:: cpp
156
157        py::class_<Pet>(m, "Pet")
158            .def(py::init<const std::string &>())
159            .def_property("name", &Pet::getName, &Pet::setName)
160            // ... remainder ...
161
162.. seealso::
163
164    Similar functions :func:`class_::def_readwrite_static`,
165    :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
166    and :func:`class_::def_property_readonly_static` are provided for binding
167    static variables and properties. Please also see the section on
168    :ref:`static_properties` in the advanced part of the documentation.
169
170Dynamic attributes
171==================
172
173Native Python classes can pick up new attributes dynamically:
174
175.. code-block:: pycon
176
177    >>> class Pet:
178    ...     name = 'Molly'
179    ...
180    >>> p = Pet()
181    >>> p.name = 'Charly'  # overwrite existing
182    >>> p.age = 2  # dynamically add a new attribute
183
184By default, classes exported from C++ do not support this and the only writable
185attributes are the ones explicitly defined using :func:`class_::def_readwrite`
186or :func:`class_::def_property`.
187
188.. code-block:: cpp
189
190    py::class_<Pet>(m, "Pet")
191        .def(py::init<>())
192        .def_readwrite("name", &Pet::name);
193
194Trying to set any other attribute results in an error:
195
196.. code-block:: pycon
197
198    >>> p = example.Pet()
199    >>> p.name = 'Charly'  # OK, attribute defined in C++
200    >>> p.age = 2  # fail
201    AttributeError: 'Pet' object has no attribute 'age'
202
203To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
204must be added to the :class:`py::class_` constructor:
205
206.. code-block:: cpp
207
208    py::class_<Pet>(m, "Pet", py::dynamic_attr())
209        .def(py::init<>())
210        .def_readwrite("name", &Pet::name);
211
212Now everything works as expected:
213
214.. code-block:: pycon
215
216    >>> p = example.Pet()
217    >>> p.name = 'Charly'  # OK, overwrite value in C++
218    >>> p.age = 2  # OK, dynamically add a new attribute
219    >>> p.__dict__  # just like a native Python class
220    {'age': 2}
221
222Note that there is a small runtime cost for a class with dynamic attributes.
223Not only because of the addition of a ``__dict__``, but also because of more
224expensive garbage collection tracking which must be activated to resolve
225possible circular references. Native Python classes incur this same cost by
226default, so this is not anything to worry about. By default, pybind11 classes
227are more efficient than native Python classes. Enabling dynamic attributes
228just brings them on par.
229
230.. _inheritance:
231
232Inheritance
233===========
234
235Suppose now that the example consists of two data structures with an
236inheritance relationship:
237
238.. code-block:: cpp
239
240    struct Pet {
241        Pet(const std::string &name) : name(name) { }
242        std::string name;
243    };
244
245    struct Dog : Pet {
246        Dog(const std::string &name) : Pet(name) { }
247        std::string bark() const { return "woof!"; }
248    };
249
250There are two different ways of indicating a hierarchical relationship to
251pybind11: the first specifies the C++ base class as an extra template
252parameter of the :class:`class_`:
253
254.. code-block:: cpp
255
256    py::class_<Pet>(m, "Pet")
257       .def(py::init<const std::string &>())
258       .def_readwrite("name", &Pet::name);
259
260    // Method 1: template parameter:
261    py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
262        .def(py::init<const std::string &>())
263        .def("bark", &Dog::bark);
264
265Alternatively, we can also assign a name to the previously bound ``Pet``
266:class:`class_` object and reference it when binding the ``Dog`` class:
267
268.. code-block:: cpp
269
270    py::class_<Pet> pet(m, "Pet");
271    pet.def(py::init<const std::string &>())
272       .def_readwrite("name", &Pet::name);
273
274    // Method 2: pass parent class_ object:
275    py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
276        .def(py::init<const std::string &>())
277        .def("bark", &Dog::bark);
278
279Functionality-wise, both approaches are equivalent. Afterwards, instances will
280expose fields and methods of both types:
281
282.. code-block:: pycon
283
284    >>> p = example.Dog('Molly')
285    >>> p.name
286    u'Molly'
287    >>> p.bark()
288    u'woof!'
289
290Overloaded methods
291==================
292
293Sometimes there are several overloaded C++ methods with the same name taking
294different kinds of input arguments:
295
296.. code-block:: cpp
297
298    struct Pet {
299        Pet(const std::string &name, int age) : name(name), age(age) { }
300
301        void set(int age) { age = age; }
302        void set(const std::string &name) { name = name; }
303
304        std::string name;
305        int age;
306    };
307
308Attempting to bind ``Pet::set`` will cause an error since the compiler does not
309know which method the user intended to select. We can disambiguate by casting
310them to function pointers. Binding multiple functions to the same Python name
311automatically creates a chain of function overloads that will be tried in
312sequence.
313
314.. code-block:: cpp
315
316    py::class_<Pet>(m, "Pet")
317       .def(py::init<const std::string &, int>())
318       .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
319       .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
320
321The overload signatures are also visible in the method's docstring:
322
323.. code-block:: pycon
324
325    >>> help(example.Pet)
326
327    class Pet(__builtin__.object)
328     |  Methods defined here:
329     |
330     |  __init__(...)
331     |      Signature : (Pet, str, int) -> NoneType
332     |
333     |  set(...)
334     |      1. Signature : (Pet, int) -> NoneType
335     |
336     |      Set the pet's age
337     |
338     |      2. Signature : (Pet, str) -> NoneType
339     |
340     |      Set the pet's name
341
342If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
343syntax to cast the overloaded function:
344
345.. code-block:: cpp
346
347    py::class_<Pet>(m, "Pet")
348        .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
349        .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
350
351Here, ``py::overload_cast`` only requires the parameter types to be specified.
352The return type and class are deduced. This avoids the additional noise of
353``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
354on constness, the ``py::const_`` tag should be used:
355
356.. code-block:: cpp
357
358    struct Widget {
359        int foo(int x, float y);
360        int foo(int x, float y) const;
361    };
362
363    py::class_<Widget>(m, "Widget")
364       .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
365       .def("foo_const",   py::overload_cast<int, float>(&Widget::foo, py::const_));
366
367
368.. [#cpp14] A compiler which supports the ``-std=c++14`` flag
369            or Visual Studio 2015 Update 2 and newer.
370
371.. note::
372
373    To define multiple overloaded constructors, simply declare one after the
374    other using the ``.def(py::init<...>())`` syntax. The existing machinery
375    for specifying keyword and default arguments also works.
376
377Enumerations and internal types
378===============================
379
380Let's now suppose that the example class contains an internal enumeration type,
381e.g.:
382
383.. code-block:: cpp
384
385    struct Pet {
386        enum Kind {
387            Dog = 0,
388            Cat
389        };
390
391        Pet(const std::string &name, Kind type) : name(name), type(type) { }
392
393        std::string name;
394        Kind type;
395    };
396
397The binding code for this example looks as follows:
398
399.. code-block:: cpp
400
401    py::class_<Pet> pet(m, "Pet");
402
403    pet.def(py::init<const std::string &, Pet::Kind>())
404        .def_readwrite("name", &Pet::name)
405        .def_readwrite("type", &Pet::type);
406
407    py::enum_<Pet::Kind>(pet, "Kind")
408        .value("Dog", Pet::Kind::Dog)
409        .value("Cat", Pet::Kind::Cat)
410        .export_values();
411
412To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
413``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
414constructor. The :func:`enum_::export_values` function exports the enum entries
415into the parent scope, which should be skipped for newer C++11-style strongly
416typed enums.
417
418.. code-block:: pycon
419
420    >>> p = Pet('Lucy', Pet.Cat)
421    >>> p.type
422    Kind.Cat
423    >>> int(p.type)
424    1L
425
426
427.. note::
428
429    When the special tag ``py::arithmetic()`` is specified to the ``enum_``
430    constructor, pybind11 creates an enumeration that also supports rudimentary
431    arithmetic and bit-level operations like comparisons, and, or, xor, negation,
432    etc.
433
434    .. code-block:: cpp
435
436        py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
437           ...
438
439    By default, these are omitted to conserve space.
440