[PyKDE] overloading __str__() for wrapped class

Glen W. Mabey Glen.Mabey at swri.org
Wed Nov 16 15:21:20 GMT 2005


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?

Thanks,
Glen Mabey




More information about the PyQt mailing list