[C++-sig] Accessing Python derived-class members from C++ base

Conan Brink conanb at STCG.net
Mon Aug 11 18:55:55 CEST 2003

Given a C++ base class "Base" and a Python class "Derived" derived from
it, I have a method in Base that needs to access arbitrary attributes of
an instance of Derived.  Is there any way to do this other than
explicitly passing an extra copy of "self" into the method calls to

A simple example of this clunky interface follows.
(yes, it's a really silly problem to be solving in this manner, but it
illustrates the interface)


namespace py = boost::python;

struct Base {
    Base() {}
    void DoubleIt(py::object self, std::string name);

void Base::DoubleIt(py::object self, std::string name)
    self.attr(name.c_str()) = self.attr(name.c_str()) * 2;

    py::def("Dist", &Dist);
    py::class_<Base>("Base", py::init<>())
        .def("DoubleIt", &Base::DoubleIt)


class Derived(Base):

d = Derived()
d.i = 1
d.a = 'Foo'
print d.i
print d.a
d.DoubleIt(d, 'i')
d.DoubleIt(d, 'a')
print d.i
print d.a

Output is, naturally:

But I'd sure like to get rid of the extra "d" in the calls to DoubleIt.


This message contains information that may be confidential and privileged.  Unless you are the addressee (or authorized to receive messages for the addressee), you may not use, copy, or disclose to anyone the message or any information contained in the message.  If you have received the message in error, please advise the sender by reply e-mail and delete the message.  Nothing in this message should be interpreted as a digital or electronic signature that can be used to authenticate a contract or any other legal document.

More information about the Cplusplus-sig mailing list