Warning, /jana2/src/python/externals/pybind11-2.10.3/docs/classes.rst is written in an unsupported language. File is not indexed.
0001 .. _classes:
0002
0003 Object-oriented code
0004 ####################
0005
0006 Creating bindings for a custom type
0007 ===================================
0008
0009 Let's now look at a more complex example where we'll create bindings for a
0010 custom C++ data structure named ``Pet``. Its definition is given below:
0011
0012 .. code-block:: cpp
0013
0014 struct Pet {
0015 Pet(const std::string &name) : name(name) { }
0016 void setName(const std::string &name_) { name = name_; }
0017 const std::string &getName() const { return name; }
0018
0019 std::string name;
0020 };
0021
0022 The binding code for ``Pet`` looks as follows:
0023
0024 .. code-block:: cpp
0025
0026 #include <pybind11/pybind11.h>
0027
0028 namespace py = pybind11;
0029
0030 PYBIND11_MODULE(example, m) {
0031 py::class_<Pet>(m, "Pet")
0032 .def(py::init<const std::string &>())
0033 .def("setName", &Pet::setName)
0034 .def("getName", &Pet::getName);
0035 }
0036
0037 :class:`class_` creates bindings for a C++ *class* or *struct*-style data
0038 structure. :func:`init` is a convenience function that takes the types of a
0039 constructor's parameters as template arguments and wraps the corresponding
0040 constructor (see the :ref:`custom_constructors` section for details). An
0041 interactive Python session demonstrating this example is shown below:
0042
0043 .. code-block:: pycon
0044
0045 % python
0046 >>> import example
0047 >>> p = example.Pet("Molly")
0048 >>> print(p)
0049 <example.Pet object at 0x10cd98060>
0050 >>> p.getName()
0051 'Molly'
0052 >>> p.setName("Charly")
0053 >>> p.getName()
0054 'Charly'
0055
0056 .. seealso::
0057
0058 Static member functions can be bound in the same way using
0059 :func:`class_::def_static`.
0060
0061 Keyword and default arguments
0062 =============================
0063 It is possible to specify keyword and default arguments using the syntax
0064 discussed in the previous chapter. Refer to the sections :ref:`keyword_args`
0065 and :ref:`default_args` for details.
0066
0067 Binding lambda functions
0068 ========================
0069
0070 Note how ``print(p)`` produced a rather useless summary of our data structure in the example above:
0071
0072 .. code-block:: pycon
0073
0074 >>> print(p)
0075 <example.Pet object at 0x10cd98060>
0076
0077 To address this, we could bind a utility function that returns a human-readable
0078 summary to the special method slot named ``__repr__``. Unfortunately, there is no
0079 suitable functionality in the ``Pet`` data structure, and it would be nice if
0080 we did not have to change it. This can easily be accomplished by binding a
0081 Lambda function instead:
0082
0083 .. code-block:: cpp
0084
0085 py::class_<Pet>(m, "Pet")
0086 .def(py::init<const std::string &>())
0087 .def("setName", &Pet::setName)
0088 .def("getName", &Pet::getName)
0089 .def("__repr__",
0090 [](const Pet &a) {
0091 return "<example.Pet named '" + a.name + "'>";
0092 }
0093 );
0094
0095 Both stateless [#f1]_ and stateful lambda closures are supported by pybind11.
0096 With the above change, the same Python code now produces the following output:
0097
0098 .. code-block:: pycon
0099
0100 >>> print(p)
0101 <example.Pet named 'Molly'>
0102
0103 .. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object.
0104
0105 .. _properties:
0106
0107 Instance and static fields
0108 ==========================
0109
0110 We can also directly expose the ``name`` field using the
0111 :func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly`
0112 method also exists for ``const`` fields.
0113
0114 .. code-block:: cpp
0115
0116 py::class_<Pet>(m, "Pet")
0117 .def(py::init<const std::string &>())
0118 .def_readwrite("name", &Pet::name)
0119 // ... remainder ...
0120
0121 This makes it possible to write
0122
0123 .. code-block:: pycon
0124
0125 >>> p = example.Pet("Molly")
0126 >>> p.name
0127 'Molly'
0128 >>> p.name = "Charly"
0129 >>> p.name
0130 'Charly'
0131
0132 Now suppose that ``Pet::name`` was a private internal variable
0133 that can only be accessed via setters and getters.
0134
0135 .. code-block:: cpp
0136
0137 class Pet {
0138 public:
0139 Pet(const std::string &name) : name(name) { }
0140 void setName(const std::string &name_) { name = name_; }
0141 const std::string &getName() const { return name; }
0142 private:
0143 std::string name;
0144 };
0145
0146 In this case, the method :func:`class_::def_property`
0147 (:func:`class_::def_property_readonly` for read-only data) can be used to
0148 provide a field-like interface within Python that will transparently call
0149 the setter and getter functions:
0150
0151 .. code-block:: cpp
0152
0153 py::class_<Pet>(m, "Pet")
0154 .def(py::init<const std::string &>())
0155 .def_property("name", &Pet::getName, &Pet::setName)
0156 // ... remainder ...
0157
0158 Write only properties can be defined by passing ``nullptr`` as the
0159 input for the read function.
0160
0161 .. seealso::
0162
0163 Similar functions :func:`class_::def_readwrite_static`,
0164 :func:`class_::def_readonly_static` :func:`class_::def_property_static`,
0165 and :func:`class_::def_property_readonly_static` are provided for binding
0166 static variables and properties. Please also see the section on
0167 :ref:`static_properties` in the advanced part of the documentation.
0168
0169 Dynamic attributes
0170 ==================
0171
0172 Native Python classes can pick up new attributes dynamically:
0173
0174 .. code-block:: pycon
0175
0176 >>> class Pet:
0177 ... name = "Molly"
0178 ...
0179 >>> p = Pet()
0180 >>> p.name = "Charly" # overwrite existing
0181 >>> p.age = 2 # dynamically add a new attribute
0182
0183 By default, classes exported from C++ do not support this and the only writable
0184 attributes are the ones explicitly defined using :func:`class_::def_readwrite`
0185 or :func:`class_::def_property`.
0186
0187 .. code-block:: cpp
0188
0189 py::class_<Pet>(m, "Pet")
0190 .def(py::init<>())
0191 .def_readwrite("name", &Pet::name);
0192
0193 Trying to set any other attribute results in an error:
0194
0195 .. code-block:: pycon
0196
0197 >>> p = example.Pet()
0198 >>> p.name = "Charly" # OK, attribute defined in C++
0199 >>> p.age = 2 # fail
0200 AttributeError: 'Pet' object has no attribute 'age'
0201
0202 To enable dynamic attributes for C++ classes, the :class:`py::dynamic_attr` tag
0203 must be added to the :class:`py::class_` constructor:
0204
0205 .. code-block:: cpp
0206
0207 py::class_<Pet>(m, "Pet", py::dynamic_attr())
0208 .def(py::init<>())
0209 .def_readwrite("name", &Pet::name);
0210
0211 Now everything works as expected:
0212
0213 .. code-block:: pycon
0214
0215 >>> p = example.Pet()
0216 >>> p.name = "Charly" # OK, overwrite value in C++
0217 >>> p.age = 2 # OK, dynamically add a new attribute
0218 >>> p.__dict__ # just like a native Python class
0219 {'age': 2}
0220
0221 Note that there is a small runtime cost for a class with dynamic attributes.
0222 Not only because of the addition of a ``__dict__``, but also because of more
0223 expensive garbage collection tracking which must be activated to resolve
0224 possible circular references. Native Python classes incur this same cost by
0225 default, so this is not anything to worry about. By default, pybind11 classes
0226 are more efficient than native Python classes. Enabling dynamic attributes
0227 just brings them on par.
0228
0229 .. _inheritance:
0230
0231 Inheritance and automatic downcasting
0232 =====================================
0233
0234 Suppose now that the example consists of two data structures with an
0235 inheritance relationship:
0236
0237 .. code-block:: cpp
0238
0239 struct Pet {
0240 Pet(const std::string &name) : name(name) { }
0241 std::string name;
0242 };
0243
0244 struct Dog : Pet {
0245 Dog(const std::string &name) : Pet(name) { }
0246 std::string bark() const { return "woof!"; }
0247 };
0248
0249 There are two different ways of indicating a hierarchical relationship to
0250 pybind11: the first specifies the C++ base class as an extra template
0251 parameter of the :class:`class_`:
0252
0253 .. code-block:: cpp
0254
0255 py::class_<Pet>(m, "Pet")
0256 .def(py::init<const std::string &>())
0257 .def_readwrite("name", &Pet::name);
0258
0259 // Method 1: template parameter:
0260 py::class_<Dog, Pet /* <- specify C++ parent type */>(m, "Dog")
0261 .def(py::init<const std::string &>())
0262 .def("bark", &Dog::bark);
0263
0264 Alternatively, we can also assign a name to the previously bound ``Pet``
0265 :class:`class_` object and reference it when binding the ``Dog`` class:
0266
0267 .. code-block:: cpp
0268
0269 py::class_<Pet> pet(m, "Pet");
0270 pet.def(py::init<const std::string &>())
0271 .def_readwrite("name", &Pet::name);
0272
0273 // Method 2: pass parent class_ object:
0274 py::class_<Dog>(m, "Dog", pet /* <- specify Python parent type */)
0275 .def(py::init<const std::string &>())
0276 .def("bark", &Dog::bark);
0277
0278 Functionality-wise, both approaches are equivalent. Afterwards, instances will
0279 expose fields and methods of both types:
0280
0281 .. code-block:: pycon
0282
0283 >>> p = example.Dog("Molly")
0284 >>> p.name
0285 'Molly'
0286 >>> p.bark()
0287 'woof!'
0288
0289 The C++ classes defined above are regular non-polymorphic types with an
0290 inheritance relationship. This is reflected in Python:
0291
0292 .. code-block:: cpp
0293
0294 // Return a base pointer to a derived instance
0295 m.def("pet_store", []() { return std::unique_ptr<Pet>(new Dog("Molly")); });
0296
0297 .. code-block:: pycon
0298
0299 >>> p = example.pet_store()
0300 >>> type(p) # `Dog` instance behind `Pet` pointer
0301 Pet # no pointer downcasting for regular non-polymorphic types
0302 >>> p.bark()
0303 AttributeError: 'Pet' object has no attribute 'bark'
0304
0305 The function returned a ``Dog`` instance, but because it's a non-polymorphic
0306 type behind a base pointer, Python only sees a ``Pet``. In C++, a type is only
0307 considered polymorphic if it has at least one virtual function and pybind11
0308 will automatically recognize this:
0309
0310 .. code-block:: cpp
0311
0312 struct PolymorphicPet {
0313 virtual ~PolymorphicPet() = default;
0314 };
0315
0316 struct PolymorphicDog : PolymorphicPet {
0317 std::string bark() const { return "woof!"; }
0318 };
0319
0320 // Same binding code
0321 py::class_<PolymorphicPet>(m, "PolymorphicPet");
0322 py::class_<PolymorphicDog, PolymorphicPet>(m, "PolymorphicDog")
0323 .def(py::init<>())
0324 .def("bark", &PolymorphicDog::bark);
0325
0326 // Again, return a base pointer to a derived instance
0327 m.def("pet_store2", []() { return std::unique_ptr<PolymorphicPet>(new PolymorphicDog); });
0328
0329 .. code-block:: pycon
0330
0331 >>> p = example.pet_store2()
0332 >>> type(p)
0333 PolymorphicDog # automatically downcast
0334 >>> p.bark()
0335 'woof!'
0336
0337 Given a pointer to a polymorphic base, pybind11 performs automatic downcasting
0338 to the actual derived type. Note that this goes beyond the usual situation in
0339 C++: we don't just get access to the virtual functions of the base, we get the
0340 concrete derived type including functions and attributes that the base type may
0341 not even be aware of.
0342
0343 .. seealso::
0344
0345 For more information about polymorphic behavior see :ref:`overriding_virtuals`.
0346
0347
0348 Overloaded methods
0349 ==================
0350
0351 Sometimes there are several overloaded C++ methods with the same name taking
0352 different kinds of input arguments:
0353
0354 .. code-block:: cpp
0355
0356 struct Pet {
0357 Pet(const std::string &name, int age) : name(name), age(age) { }
0358
0359 void set(int age_) { age = age_; }
0360 void set(const std::string &name_) { name = name_; }
0361
0362 std::string name;
0363 int age;
0364 };
0365
0366 Attempting to bind ``Pet::set`` will cause an error since the compiler does not
0367 know which method the user intended to select. We can disambiguate by casting
0368 them to function pointers. Binding multiple functions to the same Python name
0369 automatically creates a chain of function overloads that will be tried in
0370 sequence.
0371
0372 .. code-block:: cpp
0373
0374 py::class_<Pet>(m, "Pet")
0375 .def(py::init<const std::string &, int>())
0376 .def("set", static_cast<void (Pet::*)(int)>(&Pet::set), "Set the pet's age")
0377 .def("set", static_cast<void (Pet::*)(const std::string &)>(&Pet::set), "Set the pet's name");
0378
0379 The overload signatures are also visible in the method's docstring:
0380
0381 .. code-block:: pycon
0382
0383 >>> help(example.Pet)
0384
0385 class Pet(__builtin__.object)
0386 | Methods defined here:
0387 |
0388 | __init__(...)
0389 | Signature : (Pet, str, int) -> NoneType
0390 |
0391 | set(...)
0392 | 1. Signature : (Pet, int) -> NoneType
0393 |
0394 | Set the pet's age
0395 |
0396 | 2. Signature : (Pet, str) -> NoneType
0397 |
0398 | Set the pet's name
0399
0400 If you have a C++14 compatible compiler [#cpp14]_, you can use an alternative
0401 syntax to cast the overloaded function:
0402
0403 .. code-block:: cpp
0404
0405 py::class_<Pet>(m, "Pet")
0406 .def("set", py::overload_cast<int>(&Pet::set), "Set the pet's age")
0407 .def("set", py::overload_cast<const std::string &>(&Pet::set), "Set the pet's name");
0408
0409 Here, ``py::overload_cast`` only requires the parameter types to be specified.
0410 The return type and class are deduced. This avoids the additional noise of
0411 ``void (Pet::*)()`` as seen in the raw cast. If a function is overloaded based
0412 on constness, the ``py::const_`` tag should be used:
0413
0414 .. code-block:: cpp
0415
0416 struct Widget {
0417 int foo(int x, float y);
0418 int foo(int x, float y) const;
0419 };
0420
0421 py::class_<Widget>(m, "Widget")
0422 .def("foo_mutable", py::overload_cast<int, float>(&Widget::foo))
0423 .def("foo_const", py::overload_cast<int, float>(&Widget::foo, py::const_));
0424
0425 If you prefer the ``py::overload_cast`` syntax but have a C++11 compatible compiler only,
0426 you can use ``py::detail::overload_cast_impl`` with an additional set of parentheses:
0427
0428 .. code-block:: cpp
0429
0430 template <typename... Args>
0431 using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;
0432
0433 py::class_<Pet>(m, "Pet")
0434 .def("set", overload_cast_<int>()(&Pet::set), "Set the pet's age")
0435 .def("set", overload_cast_<const std::string &>()(&Pet::set), "Set the pet's name");
0436
0437 .. [#cpp14] A compiler which supports the ``-std=c++14`` flag.
0438
0439 .. note::
0440
0441 To define multiple overloaded constructors, simply declare one after the
0442 other using the ``.def(py::init<...>())`` syntax. The existing machinery
0443 for specifying keyword and default arguments also works.
0444
0445 Enumerations and internal types
0446 ===============================
0447
0448 Let's now suppose that the example class contains internal types like enumerations, e.g.:
0449
0450 .. code-block:: cpp
0451
0452 struct Pet {
0453 enum Kind {
0454 Dog = 0,
0455 Cat
0456 };
0457
0458 struct Attributes {
0459 float age = 0;
0460 };
0461
0462 Pet(const std::string &name, Kind type) : name(name), type(type) { }
0463
0464 std::string name;
0465 Kind type;
0466 Attributes attr;
0467 };
0468
0469 The binding code for this example looks as follows:
0470
0471 .. code-block:: cpp
0472
0473 py::class_<Pet> pet(m, "Pet");
0474
0475 pet.def(py::init<const std::string &, Pet::Kind>())
0476 .def_readwrite("name", &Pet::name)
0477 .def_readwrite("type", &Pet::type)
0478 .def_readwrite("attr", &Pet::attr);
0479
0480 py::enum_<Pet::Kind>(pet, "Kind")
0481 .value("Dog", Pet::Kind::Dog)
0482 .value("Cat", Pet::Kind::Cat)
0483 .export_values();
0484
0485 py::class_<Pet::Attributes>(pet, "Attributes")
0486 .def(py::init<>())
0487 .def_readwrite("age", &Pet::Attributes::age);
0488
0489
0490 To ensure that the nested types ``Kind`` and ``Attributes`` are created within the scope of ``Pet``, the
0491 ``pet`` :class:`class_` instance must be supplied to the :class:`enum_` and :class:`class_`
0492 constructor. The :func:`enum_::export_values` function exports the enum entries
0493 into the parent scope, which should be skipped for newer C++11-style strongly
0494 typed enums.
0495
0496 .. code-block:: pycon
0497
0498 >>> p = Pet("Lucy", Pet.Cat)
0499 >>> p.type
0500 Kind.Cat
0501 >>> int(p.type)
0502 1L
0503
0504 The entries defined by the enumeration type are exposed in the ``__members__`` property:
0505
0506 .. code-block:: pycon
0507
0508 >>> Pet.Kind.__members__
0509 {'Dog': Kind.Dog, 'Cat': Kind.Cat}
0510
0511 The ``name`` property returns the name of the enum value as a unicode string.
0512
0513 .. note::
0514
0515 It is also possible to use ``str(enum)``, however these accomplish different
0516 goals. The following shows how these two approaches differ.
0517
0518 .. code-block:: pycon
0519
0520 >>> p = Pet("Lucy", Pet.Cat)
0521 >>> pet_type = p.type
0522 >>> pet_type
0523 Pet.Cat
0524 >>> str(pet_type)
0525 'Pet.Cat'
0526 >>> pet_type.name
0527 'Cat'
0528
0529 .. note::
0530
0531 When the special tag ``py::arithmetic()`` is specified to the ``enum_``
0532 constructor, pybind11 creates an enumeration that also supports rudimentary
0533 arithmetic and bit-level operations like comparisons, and, or, xor, negation,
0534 etc.
0535
0536 .. code-block:: cpp
0537
0538 py::enum_<Pet::Kind>(pet, "Kind", py::arithmetic())
0539 ...
0540
0541 By default, these are omitted to conserve space.