[C++-sig] confused...
Nicodemus
nicodemus at globalite.com.br
Thu May 15 00:35:52 CEST 2003
Paul Rudin wrote:
>Should this work? If not is there an obvious way to make it work? TIA.
>
>
>Say subclassTest.cpp contains:
>
>---------------------
>#include <boost/python.hpp>
>using namespace boost::python;
>
>class Base
>{
>public:
> virtual int foo(int x) { return x+1;}
>};
>
>class Bar
>{
>public:
> Base* thing;
> void setThing(Base* bptr) { thing=bptr;};
> int callThing(int x) {return thing->foo(x);};
>};
>
>class BaseWrap : public Base
>{
>public:
> BaseWrap(PyObject* self_):self(self_){}
>
> int foo(int x)
> {
> return call_method<bool>(self,"foo",x);
> }
>
Here you mean:
return call_method<int>(self, "foo", x);
^^^
Right?
> PyObject* self;
>};
>
>
>BOOST_PYTHON_MODULE(subclassTest)
>{
>
>
> class_<Base, BaseWrap, boost::noncopyable >("Base")
> .def("foo", &BaseWrap::foo)
> ;
>
> class_<Bar>("Bar")
> .def("setThing", &Bar::setThing)
> .def("callThing", &Bar::callThing)
> ;
>
>};
>
>---------------------
>
>Then in python:
>
>
>
>>>>from subclassTest import *
>>>>class sub(Base):
>>>>
>>>>
>... def foo(z):
>... z=z+7
>...
>
Change sub to:
>>> class sub(Base):
... def foo(self, z):
... return z+7
...
Note the "self" argument in the method. In Python, the "self" ("this" in
C++) is explicity.
>>>>s=sub()
>>>>bar=Bar()
>>>>bar.setThing(s)
>>>>bar.callThing(2)
>>>>
>>>>
>Traceback (most recent call last):
> File "<stdin>", line 1, in ?
>TypeError: foo() takes exactly 1 argument (2 given)
>
>
Hope that helps,
Nicodemus.
More information about the Cplusplus-sig
mailing list