Reputation: 2337
What's the difference between the following class definitions in pybind11?
(1)
py::class_<Pet> pet(m, "Pet");
(2)
py::class_<Pet>(m, "Pet")
What's the use of pet
in pet(m, "Pet")
? I found this definition on page 42 section "5.8 Enumerations and internal types" of the documentation, which can be found here.
Upvotes: 2
Views: 893
Reputation: 3778
The first creates a named variable that you can refer to later within the same scope (as is done in the example that you reference), the second creates a (unnamed) temporary that you can only use by chaining the function calls that set more properties on the same statement. If the variable does not escape the local scope, then the only difference is syntax. Otherwise, by naming it, you could for example pass it along to one or more helper functions (e.g. for factoring out the definitions of common properties).
What is important to understand is that all Python classes, functions, etc. are run-time constructs. I.e. some Python API code needs to be called to create them, for example when the module is loaded. An object of py::class_
calls the APIs to create a Python class and to register some type info for internal pybind11
use (e.g. for casting later on). I.e. it is only a recipe to create the requested Python class, it is not that class itself. Once the Python class is created and its type info stored, the recipe object is no longer needed and can be safely destroyed (e.g. b/c by letting it go out of scope).
Upvotes: 3