Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 1 | .. _classes: |
| 2 | |
| 3 | Object-oriented code |
| 4 | #################### |
| 5 | |
| 6 | Creating bindings for a custom type |
| 7 | =================================== |
| 8 | |
| 9 | Let's now look at a more complex example where we'll create bindings for a |
| 10 | custom 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 | |
| 22 | The binding code for ``Pet`` looks as follows: |
| 23 | |
| 24 | .. code-block:: cpp |
| 25 | |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 26 | #include <pybind11/pybind11.h> |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 27 | |
Wenzel Jakob | 10e62e1 | 2015-10-15 22:46:07 +0200 | [diff] [blame] | 28 | namespace py = pybind11; |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 29 | |
Wenzel Jakob | b1b7140 | 2015-10-18 16:48:30 +0200 | [diff] [blame^] | 30 | PYBIND11_PLUGIN(example) { |
Wenzel Jakob | 8f4eb00 | 2015-10-15 18:13:33 +0200 | [diff] [blame] | 31 | py::module m("example", "pybind11 example plugin"); |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 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 |
| 42 | structure. :func:`init` is a convenience function that takes the types of a |
| 43 | constructor's parameters as template arguments and wraps the corresponding |
| 44 | constructor (see the :ref:`custom_constructors` section for details). An |
| 45 | interactive Python session demonstrating this example is shown below: |
| 46 | |
| 47 | .. code-block:: python |
| 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 | Keyword and default arguments |
| 61 | ============================= |
| 62 | It is possible to specify keyword and default arguments using the syntax |
| 63 | discussed in the previous chapter. Refer to the sections :ref:`keyword_args` |
| 64 | and :ref:`default_args` for details. |
| 65 | |
| 66 | Binding lambda functions |
| 67 | ======================== |
| 68 | |
| 69 | Note how ``print(p)`` produced a rather useless summary of our data structure in the example above: |
| 70 | |
| 71 | .. code-block:: python |
| 72 | |
| 73 | >>> print(p) |
| 74 | <example.Pet object at 0x10cd98060> |
| 75 | |
| 76 | To address this, we could bind an utility function that returns a human-readable |
| 77 | summary to the special method slot named ``__repr__``. Unfortunately, there is no |
| 78 | suitable functionality in the ``Pet`` data structure, and it would be nice if |
| 79 | we did not have to change it. This can easily be accomplished by binding a |
| 80 | Lambda function instead: |
| 81 | |
| 82 | .. code-block:: cpp |
| 83 | |
| 84 | py::class_<Pet>(m, "Pet") |
| 85 | .def(py::init<const std::string &>()) |
| 86 | .def("setName", &Pet::setName) |
| 87 | .def("getName", &Pet::getName) |
| 88 | .def("__repr__", |
| 89 | [](const Pet &a) { |
| 90 | return "<example.Pet named '" + a.name + "'>"; |
| 91 | } |
| 92 | ); |
| 93 | |
| 94 | Both stateless [#f1]_ and stateful lambda closures are supported by pybind11. |
| 95 | With the above change, the same Python code now produces the following output: |
| 96 | |
| 97 | .. code-block:: python |
| 98 | |
| 99 | >>> print(p) |
| 100 | <example.Pet named 'Molly'> |
| 101 | |
| 102 | Instance and static fields |
| 103 | ========================== |
| 104 | |
| 105 | We can also directly expose the ``name`` field using the |
| 106 | :func:`class_::def_readwrite` method. A similar :func:`class_::def_readonly` |
| 107 | method also exists for ``const`` fields. |
| 108 | |
| 109 | .. code-block:: cpp |
| 110 | |
| 111 | py::class_<Pet>(m, "Pet") |
| 112 | .def(py::init<const std::string &>()) |
| 113 | .def_readwrite("name", &Pet::name) |
| 114 | // ... remainder ... |
| 115 | |
| 116 | This makes it possible to write |
| 117 | |
| 118 | .. code-block:: python |
| 119 | |
| 120 | >>> p = example.Pet('Molly') |
| 121 | >>> p.name |
| 122 | u'Molly' |
| 123 | >>> p.name = 'Charly' |
| 124 | >>> p.name |
| 125 | u'Charly' |
| 126 | |
| 127 | Now suppose that ``Pet::name`` was a private internal variable |
| 128 | that can only be accessed via setters and getters. |
| 129 | |
| 130 | .. code-block:: cpp |
| 131 | |
| 132 | class Pet { |
| 133 | public: |
| 134 | Pet(const std::string &name) : name(name) { } |
| 135 | void setName(const std::string &name_) { name = name_; } |
| 136 | const std::string &getName() const { return name; } |
| 137 | private: |
| 138 | std::string name; |
| 139 | }; |
| 140 | |
| 141 | In this case, the method :func:`class_::def_property` |
| 142 | (:func:`class_::def_property_readonly` for read-only data) can be used to |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 143 | provide a field-like interface within Python that will transparently call |
| 144 | the setter and getter functions: |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 145 | |
| 146 | .. code-block:: cpp |
| 147 | |
| 148 | py::class_<Pet>(m, "Pet") |
| 149 | .def(py::init<const std::string &>()) |
| 150 | .def_property("name", &Pet::getName, &Pet::setName) |
| 151 | // ... remainder ... |
| 152 | |
| 153 | .. seealso:: |
| 154 | |
| 155 | Similar functions :func:`class_::def_readwrite_static`, |
| 156 | :func:`class_::def_readonly_static` :func:`class_::def_property_static`, |
| 157 | and :func:`class_::def_property_readonly_static` are provided for binding |
| 158 | static variables and properties. |
| 159 | |
| 160 | Inheritance |
| 161 | =========== |
| 162 | |
| 163 | Suppose now that the example consists of two data structures with an |
| 164 | inheritance relationship: |
| 165 | |
| 166 | .. code-block:: cpp |
| 167 | |
| 168 | struct Pet { |
| 169 | Pet(const std::string &name) : name(name) { } |
| 170 | std::string name; |
| 171 | }; |
| 172 | |
| 173 | struct Dog : Pet { |
| 174 | Dog(const std::string &name) : Pet(name) { } |
| 175 | std::string bark() const { return "woof!"; } |
| 176 | }; |
| 177 | |
| 178 | To capture the hierarchical relationship in pybind11, we must assign a name to |
| 179 | the ``Pet`` :class:`class_` instance and reference it when binding the ``Dog`` |
| 180 | class. |
| 181 | |
| 182 | .. code-block:: cpp |
| 183 | |
| 184 | py::class_<Pet> pet(m, "Pet"); |
| 185 | pet.def(py::init<const std::string &>()) |
| 186 | .def_readwrite("name", &Pet::name); |
| 187 | |
| 188 | py::class_<Dog>(m, "Dog", pet /* <- specify parent */) |
| 189 | .def(py::init<const std::string &>()) |
| 190 | .def("bark", &Dog::bark); |
| 191 | |
| 192 | Instances then expose fields and methods of both types: |
| 193 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 194 | .. code-block:: python |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 195 | |
| 196 | >>> p = example.Dog('Molly') |
| 197 | >>> p.name |
| 198 | u'Molly' |
| 199 | >>> p.bark() |
| 200 | u'woof!' |
| 201 | |
| 202 | Overloaded methods |
| 203 | ================== |
| 204 | |
| 205 | Sometimes there are several overloaded C++ methods with the same name taking |
| 206 | different kinds of input arguments: |
| 207 | |
| 208 | .. code-block:: cpp |
| 209 | |
| 210 | struct Pet { |
| 211 | Pet(const std::string &name, int age) : name(name), age(age) { } |
| 212 | |
| 213 | void set(int age) { age = age; } |
| 214 | void set(const std::string &name) { name = name; } |
| 215 | |
| 216 | std::string name; |
| 217 | int age; |
| 218 | }; |
| 219 | |
| 220 | Attempting to bind ``Pet::set`` will cause an error since the compiler does not |
| 221 | know which method the user intended to select. We can disambiguate by casting |
| 222 | them to function pointers. Binding multiple functions to the same Python name |
| 223 | automatically creates a chain of fucnction overloads that will be tried in |
| 224 | sequence. |
| 225 | |
| 226 | .. code-block:: cpp |
| 227 | |
| 228 | py::class_<Pet>(m, "Pet") |
| 229 | .def(py::init<const std::string &, int>()) |
| 230 | .def("set", (void (Pet::*)(int)) &Pet::set, "Set the pet's age") |
| 231 | .def("set", (void (Pet::*)(const std::string &)) &Pet::set, "Set the pet's name"); |
| 232 | |
| 233 | The overload signatures are also visible in the method's docstring: |
| 234 | |
| 235 | .. code-block:: python |
| 236 | |
| 237 | >>> help(example.Pet) |
| 238 | |
| 239 | class Pet(__builtin__.object) |
| 240 | | Methods defined here: |
| 241 | | |
| 242 | | __init__(...) |
| 243 | | Signature : (Pet, str, int32_t) -> None |
| 244 | | |
| 245 | | set(...) |
| 246 | | 1. Signature : (Pet, int32_t) -> None |
| 247 | | |
| 248 | | Set the pet's age |
| 249 | | |
| 250 | | 2. Signature : (Pet, str) -> None |
| 251 | | |
| 252 | | Set the pet's name |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 253 | |
| 254 | .. note:: |
| 255 | |
| 256 | To define multiple overloaded constructors, simply declare one after the |
| 257 | other using the ``.def(py::init<...>())`` syntax. The existing machinery |
| 258 | for specifying keyword and default arguments also works. |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 259 | |
| 260 | Enumerations and internal types |
| 261 | =============================== |
| 262 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 263 | Let's now suppose that the example class contains an internal enumeration type, |
| 264 | e.g.: |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 265 | |
| 266 | .. code-block:: cpp |
| 267 | |
| 268 | struct Pet { |
| 269 | enum Kind { |
| 270 | Dog = 0, |
| 271 | Cat |
| 272 | }; |
| 273 | |
| 274 | Pet(const std::string &name, Kind type) : name(name), type(type) { } |
| 275 | |
| 276 | std::string name; |
| 277 | Kind type; |
| 278 | }; |
| 279 | |
| 280 | The binding code for this example looks as follows: |
| 281 | |
| 282 | .. code-block:: cpp |
| 283 | |
| 284 | py::class_<Pet> pet(m, "Pet"); |
| 285 | |
| 286 | pet.def(py::init<const std::string &, Pet::Kind>()) |
| 287 | .def_readwrite("name", &Pet::name) |
| 288 | .def_readwrite("type", &Pet::type); |
| 289 | |
| 290 | py::enum_<Pet::Kind>(pet, "Kind") |
| 291 | .value("Dog", Pet::Kind::Dog) |
| 292 | .value("Cat", Pet::Kind::Cat) |
| 293 | .export_values(); |
| 294 | |
| 295 | To ensure that the ``Kind`` type is created within the scope of ``Pet``, the |
| 296 | ``pet`` :class:`class_` instance must be supplied to the :class:`enum_`. |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 297 | constructor. The :func:`enum_::export_values` function exports the enum entries |
| 298 | into the parent scope, which should be skipped for newer C++11-style strongly |
| 299 | typed enums. |
Wenzel Jakob | 28f98aa | 2015-10-13 02:57:16 +0200 | [diff] [blame] | 300 | |
| 301 | .. code-block:: python |
| 302 | |
| 303 | >>> p = Pet('Lucy', Pet.Cat) |
| 304 | >>> p.type |
| 305 | Kind.Cat |
| 306 | >>> int(p.type) |
| 307 | 1L |
| 308 | |
| 309 | |
Wenzel Jakob | 9329669 | 2015-10-13 23:21:54 +0200 | [diff] [blame] | 310 | .. [#f1] Stateless closures are those with an empty pair of brackets ``[]`` as the capture object. |