@@ -291,24 +291,28 @@ PYDRAKE_MODULE(analysis, m) {
291291 auto cls = DefineTemplateClassWithDefault<Simulator<T>>(
292292 m, " Simulator" , GetPyParam<T>(), doc.Simulator .doc );
293293 cls // BR
294- .def (py::init ([](const System<T>& system, py::object py_context) {
295- // Handle the two cases for context ownership explicitly:
296- // 1. If py_context is None, create a new context and take ownership.
297- // 2. If py_context is provided, use the existing Python wrapper
298- // directly (it already owns the C++ object).
299- if (py_context.is_none ()) {
300- std::unique_ptr<Context<T>> context_ptr =
301- system.CreateDefaultContext ();
302- // Use take_ownership because we just created this context and need
303- // Python to own it. The unique_ptr is released, leaving the raw
304- // pointer with no owner until take_ownership establishes Python
305- // ownership.
306- py_context =
307- py::cast (context_ptr.release (), py_rvp::take_ownership);
308- }
309- return Simulator<T>::MakeWithSharedContext (
310- system, make_shared_ptr_from_py_object<Context<T>>(py_context));
311- }),
294+ .def (
295+ " __init__" ,
296+ [](Simulator<T>* self, const System<T>& system,
297+ py::object py_context) {
298+ // Handle the two cases for context ownership explicitly:
299+ // 1. If py_context is None, create a new context and take
300+ // ownership.
301+ // 2. If py_context is provided, use the existing Python wrapper
302+ // directly (it already owns the C++ object).
303+ if (py_context.is_none ()) {
304+ std::unique_ptr<Context<T>> context_ptr =
305+ system.CreateDefaultContext ();
306+ // Use take_ownership because we just created this context and
307+ // need Python to own it. The unique_ptr is released, leaving
308+ // the raw pointer with no owner until take_ownership
309+ // establishes Python ownership.
310+ py_context =
311+ py::cast (context_ptr.release (), py_rvp::take_ownership);
312+ }
313+ Simulator<T>::EmplaceWithSharedContext (self, system,
314+ make_shared_ptr_from_py_object<Context<T>>(py_context));
315+ },
312316 py::arg (" system" ), py::arg (" context" ) = py::none (),
313317 // Keep alive, reference: `self` keeps `system` alive.
314318 py::keep_alive<1 , 2 >(),
0 commit comments