File tree Expand file tree Collapse file tree 2 files changed +13
-9
lines changed Expand file tree Collapse file tree 2 files changed +13
-9
lines changed Original file line number Diff line number Diff line change @@ -1370,27 +1370,29 @@ One just need to rely on the `casting capabilities`_ of `pybind11`:
1370
1370
# test.py
1371
1371
from test import Base
1372
1372
1373
+
1373
1374
class Derived (Base ):
1374
1375
def __init__ (self ):
1375
1376
Base.__init__ (self )
1376
1377
self .foo = " hello"
1377
1378
1379
+
1378
1380
b = Derived()
1379
1381
assert b.get_foo() == " hello"
1380
1382
assert not hasattr (b, " bar" )
1381
1383
1382
1384
b.set_bar()
1383
- assert b.bar == 10 .
1385
+ assert b.bar == 10.0
1384
1386
1385
1387
1386
1388
However, there is a special case where such a behavior needs a hint to work as expected:
1387
1389
when the C++ constructor is called, the C++ object is not yet allocated and registered,
1388
1390
making impossible the casting operation.
1389
1391
1390
- It's thus impossible to access the Python object from the C++ constructor one *as is *.
1392
+ It's thus impossible to access the Python object from the C++ constructor one *as is *.
1391
1393
1392
- Adding the ``py::preallocate() `` extra option to a constructor binding definition informs
1393
- `pybind11 ` to allocate the memory and register the object location just before calling the C++
1394
+ Adding the ``py::preallocate() `` extra option to a constructor binding definition informs
1395
+ `pybind11 ` to allocate the memory and register the object location just before calling the C++
1394
1396
constructor, enabling the use of ``py::cast(this) ``:
1395
1397
1396
1398
@@ -1417,12 +1419,14 @@ constructor, enabling the use of ``py::cast(this)``:
1417
1419
# test.py
1418
1420
from test import Base
1419
1421
1422
+
1420
1423
class Derived (Base ):
1421
1424
...
1422
1425
1426
+
1423
1427
b = Derived()
1424
1428
assert hasattr (b, " bar" )
1425
- assert b.bar == 10 .
1429
+ assert b.bar == 10.0
1426
1430
1427
1431
1428
1432
.. _casting capabilities : https://pybind11.readthedocs.io/en/stable/advanced/pycpp/object.html?highlight=cast#casting-back-and-forth
Original file line number Diff line number Diff line change @@ -554,8 +554,8 @@ class Derived2(m.InitPyFromCpp2):
554
554
a = m .InitPyFromCppDynamic1 ()
555
555
with pytest .raises (AttributeError ):
556
556
a .bar
557
-
558
- # works fine
557
+
558
+ # works fine
559
559
assert m .InitPyFromCppDynamic2 ().bar == 10.0
560
560
561
561
# 4. on derived class of base supporting dynamic attributes
@@ -567,8 +567,8 @@ class DynamicDerived1(m.InitPyFromCppDynamic1):
567
567
with pytest .raises (AttributeError ):
568
568
d .bar
569
569
570
- # works fine
570
+ # works fine
571
571
class DynamicDerived2 (m .InitPyFromCppDynamic2 ):
572
572
...
573
573
574
- assert DynamicDerived2 ().bar == 10.0
574
+ assert DynamicDerived2 ().bar == 10.0
You can’t perform that action at this time.
0 commit comments