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_MODULE(example, m) {
31        py::class_<Pet>(m, "Pet")
32            .def(py::init<const std::string &>())
33            .def("setName", &Pet::setName)
34            .def("getName", &Pet::getName);
35    }
36
37:class:`class_` creates bindings for a C++ *class* or *struct*-style data
38structure. :func:`init` is a convenience function that takes the types of a
39constructor's parameters as template arguments and wraps the corresponding
40constructor (see the :ref:`custom_constructors` section for details). An
41interactive Python session demonstrating this example is shown below:
42
43.. code-block:: pycon
44
45    % python
46    >>> import example
47    >>> p = example.Pet('Molly')
48    >>> print(p)
49    <example.Pet object at 0x10cd98060>
50    >>> p.getName()
51    u'Molly'
52    >>> p.setName('Charly')
53    >>> p.getName()
54    u'Charly'
55
56.. seealso::
57
58    Static member functions can be bound in the same way using
59    :func:`class_::def_static`.
60
61Keyword and default arguments
62=============================
63It is possible to specify keyword and default arguments using the syntax
64discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
65and :ref:`default_args` for details.
66
67Binding lambda functions
68========================
69
70Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
71
72.. code-block:: pycon
73
74    >>> print(p)
75    <example.Pet object at 0x10cd98060>
76
77To address this, we could bind an utility function that returns a human-readable
78summary to the special method slot named ``__repr__``. Unfortunately, there is no
79suitable functionality in the ``Pet`` data structure, and it would be nice if
80we did not have to change it. This can easily be accomplished by binding a
81Lambda function instead:
82
83.. code-block:: cpp
84
85        py::class_<Pet>(m, "Pet")
86            .def(py::init<const std::string &>())
87            .def("setName", &Pet::setName)
88            .def("getName", &Pet::getName)
89            .def("__repr__",
90                [](const Pet &a) {
91                    return "<example.Pet named '" + a.name + "'>";
92                }
93            );
94
95Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
96With the above change, the same Python code now produces the following output:
97
98.. code-block:: pycon
99
100    >>> print(p)
101    <example.Pet named 'Molly'>
102
103.. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.
104
105.. _properties:
106
107Instance and static fields
108==========================
109
110We can also directly expose the ``name`` field using the
111:func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
112method also exists for ``const`` fields.
113
114.. code-block:: cpp
115
116        py::class_<Pet>(m, "Pet")
117            .def(py::init<const std::string &>())
118            .def_readwrite("name", &Pet::name)
119            // ... remainder ...
120
121This makes it possible to write
122
123.. code-block:: pycon
124
125    >>> p = example.Pet('Molly')
126    >>> p.name
127    u'Molly'
128    >>> p.name = 'Charly'
129    >>> p.name
130    u'Charly'
131
132Now suppose that ``Pet::name`` was a private internal variable
133that can only be accessed via setters and getters.
134
135.. code-block:: cpp
136
137    class Pet {
138    public:
139        Pet(const std::string &name) : name(name) { }
140        void setName(const std::string &name_) { name = name_; }
141        const std::string &getName() const { return name; }
142    private:
143        std::string name;
144    };
145
146In this case, the method :func:`class_::def_property`
147(:func:`class_::def_property_readonly` for read-only data) can be used to
148provide a field-like interface within Python that will transparently call
149the setter and getter functions:
150
151.. code-block:: cpp
152
153        py::class_<Pet>(m, "Pet")
154            .def(py::init<const std::string &>())
155            .def_property("name", &Pet::getName, &Pet::setName)
156            // ... remainder ...
157
158Write only properties can be defined by passing ``nullptr`` as the
159input for the read function.
160
161.. seealso::
162
163    Similar functions :func:`class_::def_readwrite_static`,
164    :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
165    and :func:`class_::def_property_readonly_static` are provided for binding
166    static variables and properties. Please also see the section on
167    :ref:`static_properties` in the advanced part of the documentation.
168
169Dynamic attributes
170==================
171
172Native Python classes can pick up new attributes dynamically:
173
174.. code-block:: pycon
175
176    >>> class Pet:
177    ...     name = 'Molly'
178    ...
179    >>> p = Pet()
180    >>> p.name = 'Charly'  # overwrite existing
181    >>> p.age = 2  # dynamically add a new attribute
182
183By default, classes exported from C++ do not support this and the only writable
184attributes are the ones explicitly defined using :func:`class_::def_readwrite`
185or :func:`class_::def_property`.
186
187.. code-block:: cpp
188
189    py::class_<Pet>(m, "Pet")
190        .def(py::init<>())
191        .def_readwrite("name", &Pet::name);
192
193Trying to set any other attribute results in an error:
194
195.. code-block:: pycon
196
197    >>> p = example.Pet()
198    >>> p.name = 'Charly'  # OK, attribute defined in C++
199    >>> p.age = 2  # fail
200    AttributeError: 'Pet' object has no attribute 'age'
201
202To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
203must be added to the :class:`py::class_` constructor:
204
205.. code-block:: cpp
206
207    py::class_<Pet>(m, "Pet", py::dynamic_attr())
208        .def(py::init<>())
209        .def_readwrite("name", &Pet::name);
210
211Now everything works as expected:
212
213.. code-block:: pycon
214
215    >>> p = example.Pet()
216    >>> p.name = 'Charly'  # OK, overwrite value in C++
217    >>> p.age = 2  # OK, dynamically add a new attribute
218    >>> p.__dict__  # just like a native Python class
219    {'age': 2}
220
221Note that there is a small runtime cost for a class with dynamic attributes.
222Not only because of the addition of a ``__dict__``, but also because of more
223expensive garbage collection tracking which must be activated to resolve
224possible circular references. Native Python classes incur this same cost by
225default, so this is not anything to worry about. By default, pybind11 classes
226are more efficient than native Python classes. Enabling dynamic attributes
227just brings them on par.
228
229.. _inheritance:
230
231Inheritance and automatic downcasting
232=====================================
233
234Suppose now that the example consists of two data structures with an
235inheritance relationship:
236
237.. code-block:: cpp
238
239    struct Pet {
240        Pet(const std::string &name) : name(name) { }
241        std::string name;
242    };
243
244    struct Dog : Pet {
245        Dog(const std::string &name) : Pet(name) { }
246        std::string bark() const { return "woof!"; }
247    };
248
249There are two different ways of indicating a hierarchical relationship to
250pybind11: the first specifies the C++ base class as an extra template
251parameter of the :class:`class_`:
252
253.. code-block:: cpp
254
255    py::class_<Pet>(m, "Pet")
256       .def(py::init<const std::string &>())
257       .def_readwrite("name", &Pet::name);
258
259    // Method 1: template parameter:
260    py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
261        .def(py::init<const std::string &>())
262        .def("bark", &Dog::bark);
263
264Alternatively, we can also assign a name to the previously bound ``Pet``
265:class:`class_` object and reference it when binding the ``Dog`` class:
266
267.. code-block:: cpp
268
269    py::class_<Pet> pet(m, "Pet");
270    pet.def(py::init<const std::string &>())
271       .def_readwrite("name", &Pet::name);
272
273    // Method 2: pass parent class_ object:
274    py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
275        .def(py::init<const std::string &>())
276        .def("bark", &Dog::bark);
277
278Functionality-wise, both approaches are equivalent. Afterwards, instances will
279expose fields and methods of both types:
280
281.. code-block:: pycon
282
283    >>> p = example.Dog('Molly')
284    >>> p.name
285    u'Molly'
286    >>> p.bark()
287    u'woof!'
288
289The C++ classes defined above are regular non-polymorphic types with an
290inheritance relationship. This is reflected in Python:
291
292.. code-block:: cpp
293
294    // Return a base pointer to a derived instance
295    m.def("pet_store", []() { return std::unique_ptr<Pet>(new Dog("Molly")); });
296
297.. code-block:: pycon
298
299    >>> p = example.pet_store()
300    >>> type(p)  # `Dog` instance behind `Pet` pointer
301    Pet          # no pointer downcasting for regular non-polymorphic types
302    >>> p.bark()
303    AttributeError: 'Pet' object has no attribute 'bark'
304
305The function returned a ``Dog`` instance, but because it's a non-polymorphic
306type behind a base pointer, Python only sees a ``Pet``. In C++, a type is only
307considered polymorphic if it has at least one virtual function and pybind11
308will automatically recognize this:
309
310.. code-block:: cpp
311
312    struct PolymorphicPet {
313        virtual ~PolymorphicPet() = default;
314    };
315
316    struct PolymorphicDog : PolymorphicPet {
317        std::string bark() const { return "woof!"; }
318    };
319
320    // Same binding code
321    py::class_<PolymorphicPet>(m, "PolymorphicPet");
322    py::class_<PolymorphicDog, PolymorphicPet>(m, "PolymorphicDog")
323        .def(py::init<>())
324        .def("bark", &PolymorphicDog::bark);
325
326    // Again, return a base pointer to a derived instance
327    m.def("pet_store2", []() { return std::unique_ptr<PolymorphicPet>(new PolymorphicDog); });
328
329.. code-block:: pycon
330
331    >>> p = example.pet_store2()
332    >>> type(p)
333    PolymorphicDog  # automatically downcast
334    >>> p.bark()
335    u'woof!'
336
337Given a pointer to a polymorphic base, pybind11 performs automatic downcasting
338to the actual derived type. Note that this goes beyond the usual situation in
339C++: we don't just get access to the virtual functions of the base, we get the
340concrete derived type including functions and attributes that the base type may
341not even be aware of.
342
343.. seealso::
344
345    For more information about polymorphic behavior see :ref:`overriding_virtuals`.
346
347
348Overloaded methods
349==================
350
351Sometimes there are several overloaded C++ methods with the same name taking
352different kinds of input arguments:
353
354.. code-block:: cpp
355
356    struct Pet {
357        Pet(const std::string &name, int age) : name(name), age(age) { }
358
359        void set(int age_) { age = age_; }
360        void set(const std::string &name_) { name = name_; }
361
362        std::string name;
363        int age;
364    };
365
366Attempting to bind ``Pet::set`` will cause an error since the compiler does not
367know which method the user intended to select. We can disambiguate by casting
368them to function pointers. Binding multiple functions to the same Python name
369automatically creates a chain of function overloads that will be tried in
370sequence.
371
372.. code-block:: cpp
373
374    py::class_<Pet>(m, "Pet")
375       .def(py::init<const std::string &, int>())
376       .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age")
377       .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name");
378
379The overload signatures are also visible in the method's docstring:
380
381.. code-block:: pycon
382
383    >>> help(example.Pet)
384
385    class Pet(__builtin__.object)
386     |  Methods defined here:
387     |
388     |  __init__(...)
389     |      Signature : (Pet, str, int) -> NoneType
390     |
391     |  set(...)
392     |      1. Signature : (Pet, int) -> NoneType
393     |
394     |      Set the pet's age
395     |
396     |      2. Signature : (Pet, str) -> NoneType
397     |
398     |      Set the pet's name
399
400If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
401syntax to cast the overloaded function:
402
403.. code-block:: cpp
404
405    py::class_<Pet>(m, "Pet")
406        .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
407        .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
408
409Here, ``py::overload_cast`` only requires the parameter types to be specified.
410The return type and class are deduced. This avoids the additional noise of
411``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
412on constness, the ``py::const_`` tag should be used:
413
414.. code-block:: cpp
415
416    struct Widget {
417        int foo(int x, float y);
418        int foo(int x, float y) const;
419    };
420
421    py::class_<Widget>(m, "Widget")
422       .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
423       .def("foo_const",   py::overload_cast<int, float>(&Widget::foo, py::const_));
424
425If you prefer the ``py::overload_cast`` syntax but have a C++11 compatible compiler only,
426you can use ``py::detail::overload_cast_impl`` with an additional set of parentheses:
427
428.. code-block:: cpp
429
430    template <typename... Args>
431    using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;
432
433    py::class_<Pet>(m, "Pet")
434        .def("set", overload_cast_<int>()(&Pet::set), "Set the pet's age")
435        .def("set", overload_cast_<const std::string &>()(&Pet::set), "Set the pet's name");
436
437.. [#cpp14] A compiler which supports the ``-std=c++14`` flag
438            or Visual Studio 2015 Update 2 and newer.
439
440.. note::
441
442    To define multiple overloaded constructors, simply declare one after the
443    other using the ``.def(py::init<...>())`` syntax. The existing machinery
444    for specifying keyword and default arguments also works.
445
446Enumerations and internal types
447===============================
448
449Let's now suppose that the example class contains an internal enumeration type,
450e.g.:
451
452.. code-block:: cpp
453
454    struct Pet {
455        enum Kind {
456            Dog = 0,
457            Cat
458        };
459
460        Pet(const std::string &name, Kind type) : name(name), type(type) { }
461
462        std::string name;
463        Kind type;
464    };
465
466The binding code for this example looks as follows:
467
468.. code-block:: cpp
469
470    py::class_<Pet> pet(m, "Pet");
471
472    pet.def(py::init<const std::string &, Pet::Kind>())
473        .def_readwrite("name", &Pet::name)
474        .def_readwrite("type", &Pet::type);
475
476    py::enum_<Pet::Kind>(pet, "Kind")
477        .value("Dog", Pet::Kind::Dog)
478        .value("Cat", Pet::Kind::Cat)
479        .export_values();
480
481To ensure that the ``Kind`` type is created within the scope of ``Pet``, the
482``pet`` :class:`class_` instance must be supplied to the :class:`enum_`.
483constructor. The :func:`enum_::export_values` function exports the enum entries
484into the parent scope, which should be skipped for newer C++11-style strongly
485typed enums.
486
487.. code-block:: pycon
488
489    >>> p = Pet('Lucy', Pet.Cat)
490    >>> p.type
491    Kind.Cat
492    >>> int(p.type)
493    1L
494
495The entries defined by the enumeration type are exposed in the ``__members__`` property:
496
497.. code-block:: pycon
498
499    >>> Pet.Kind.__members__
500    {'Dog': Kind.Dog, 'Cat': Kind.Cat}
501
502The ``name`` property returns the name of the enum value as a unicode string.
503
504.. note::
505
506    It is also possible to use ``str(enum)``, however these accomplish different
507    goals. The following shows how these two approaches differ.
508
509    .. code-block:: pycon
510
511        >>> p = Pet( "Lucy", Pet.Cat )
512        >>> pet_type = p.type
513        >>> pet_type
514        Pet.Cat
515        >>> str(pet_type)
516        'Pet.Cat'
517        >>> pet_type.name
518        'Cat'
519
520.. note::
521
522    When the special tag ``py::arithmetic()`` is specified to the ``enum_``
523    constructor, pybind11 creates an enumeration that also supports rudimentary
524    arithmetic and bit-level operations like comparisons, and, or, xor, negation,
525    etc.
526
527    .. code-block:: cpp
528
529        py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
530           ...
531
532    By default, these are omitted to conserve space.
533