[PyKDE] overloading __str__() for wrapped class

Phil Thompson phil at riverbankcomputing.co.uk
Wed Nov 16 17:29:57 GMT 2005


On Wednesday 16 November 2005 3:21 pm, Glen W. Mabey wrote:
> I am trying to implement a default print method for an enum that is part
> of a C++ class definition.
>
> That is, given
>
> ***** clusty.h ***** ***** ***** ***** *****
>
> #ifndef _CLUSTY_H_
> #define _CLUSTY_H_
>
> #include <iostream>
>
> class clusty
> {
> public:
>     clusty( int i );
>     ~clusty( );
>     typedef enum { STATE0, STATE1, STATE2 } ResourceState;
>     void printit() const;
>     int get_it() const;
>     ResourceState rs;
> private:
>     int it;
> };
>
> #endif
> ***** clusty.cpp ***** ***** ***** ***** *****
>
> #include "clusty.h"
>
> clusty::clusty( int i ) : it( i ), rs( STATE1 ) { };
>
> clusty::~clusty( ) { };
>
> int clusty::get_it() const
> {
>     return it;
> }
>
> void clusty::printit( ) const
> {
>     std::cout << "it = " << it << std::endl;
>     std::cout << "rs = " << rs << std::endl;
> };
>
> ***** clusty.sip ***** ***** ***** ***** *****
>
> %Module clusty 0
>
> class clusty
> {
>
> %TypeHeaderCode
>     #include "clusty.h"
> %End
>
> public:
>     clusty( int );
>     ~clusty( );
>     enum ResourceState { STATE0, STATE1, STATE2 };
>     void printit( ) const;
>     int get_it( ) const;
>     ResourceState rs;
> };
>
> ***** ***** ***** ***** ***** *****
>
> and a pure python function like:
>
> def clustyPrint( a_c ):
>     if a_c.rc == a_c.STATE0:
>         return "Value " + `a_c.get_it()` + " at State 0"
>     if a_c.rc == a_c.STATE1:
>         return "Value " + `a_c.get_it()` + " at State 1"
>     if a_c.rc == a_c.STATE2:
>         return "Value " + `a_c.get_it()` + " at State 2"
>     return "Value " + `a_c.get_it()` + " at Unknown State"
>
> from clusty import *
> c = clusty(8)
> c.__str__ = clustyPrint_rs
> print c
>
>
> that then the last line would actually run clustyPrint().  Is this type
> of procedure possible?

If you want to do it in Python then you need to sub-class clusty and define a 
__str__() method.

If you want to do it in C++ then define a __str__() method in clusty.sip and 
use %MethodCode to implement it.

Phil




More information about the PyQt mailing list