Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamically attaching a method to an existing Python object generated with swig?
    text
    copied!<p>I am working with a Python class, and I don't have write access to its declaration. How can I attach a custom method (such as <strong><code>__str__</code></strong>) to the objects created from that class without modifying the class declaration?</p> <p>EDIT: Thank you for all your answers. I tried them all but they haven't resolved my problem. Here is a minimal example that I hope will clarify the issue. I am using swig to wrap a C++ class, and the purpose is to override the <code>__str__</code> function of <strong>an object</strong> returned by the swig module. I use cmake to build the example:</p> <p><strong>test.py</strong></p> <pre><code>import example ex = example.generate_example(2) def prnt(self): return str(self.x) #How can I replace the __str__ function of object ex with prnt? print ex print prnt(ex) </code></pre> <p><strong>example.hpp</strong></p> <pre><code>struct example { int x; }; example generate_example(int x); </code></pre> <p><strong>example.cpp</strong></p> <pre><code>#include "example.hpp" #include &lt;iostream&gt; example generate_example(int x) { example ex; ex.x = x; return ex; } int main() { example ex = generate_example(2); std::cout &lt;&lt; ex.x &lt;&lt; "\n"; return 1; } </code></pre> <p><strong>example.i</strong></p> <pre><code>%module example %{ #include "example.hpp" %} %include "example.hpp" </code></pre> <p><strong>CMakeLists.txt</strong></p> <pre><code>cmake_minimum_required(VERSION 2.6) find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) find_package(PythonLibs) include_directories(${PYTHON_INCLUDE_PATH}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) set_source_files_properties(example.i PROPERTIES CPLUSPLUS ON) swig_add_module(example python example.i example) swig_link_libraries(example ${PYTHON_LIBRARIES}) if(APPLE) set(CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS "${CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS} -flat_namespace") endif(APPLE) </code></pre> <p>To build and run test.py, copy all the files in a directory, and in that directory run</p> <pre><code>cmake . make python test.py </code></pre> <p>This results in the following output:</p> <pre><code>&lt;example.example; proxy of &lt;Swig Object of type 'example *' at 0x10021cc40&gt; &gt; 2 </code></pre> <p>As you can see the swig object has its own <strong>str</strong> function, and that is what I am trying to override. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload