基于boost::python,Python中继承C++的类型并覆写虚方法

官方文档的Wrapper建议

C++代码:

class TestBase
{
public:
    virtual void f() 
    {
        cout<<"cpp: call TestBase f"<
{
public:
    void f() override
    {
        cout << "cpp: call TestBaseWrapper f" << endl;
        if (auto f = this->get_override("f"))
        {
            f();
            return;
        }
        this->TestBase::f();
    }

    void default_f() 
    {
        cout << "cpp: call TestBaseWrapper default_f" << endl;
        this->TestBase::f();
    }
};
class_("TestBase", init<>())
    .def("f", &TestBase::f, &TestBaseWrapper::default_f)
    ;

python 调用

Python测试代码:

TestBase().f()

cpp: call TestBaseWrapper default_f
cpp: call TestBase f

class TestPySub1(TestBase):
    pass
TestPySub1().f()

cpp: call TestBaseWrapper default_f
cpp: call TestBase f

class TestPySub2(TestBase):
    def f(self):
        print "py: call TestPySub2 f"
TestPySub2().f()

py: call TestPySub2 f

结论:

从python层调用 f()

未覆写方法 -> TestBaseWrapper::default_f()

已覆写 -> py覆写的 f()


C++ 调用

C++代码:

void test(TestBase* obj)
{
    obj->f();
}

def("test", &test);

Python测试代码:

test(TestBase())

cpp: call TestBaseWrapper f
cpp: call TestBase f

class TestPySub1(TestBase):
    pass
test(TestPySub1())

cpp: call TestBaseWrapper f
cpp: call TestBase f

class TestPySub2(TestBase):
    def f(self):
        print "py: call TestPySub2 f"
test(TestPySub2())

cpp: call TestBaseWrapper f
py: call TestPySub2 f

结论:

从C++层调用 f()

调用TestBaseWrapper::f()

未覆写方法 -> TestBase::f()

已覆写 -> py覆写的 f()


尝试简化

C++代码:

class TestBase :public wrapper
{
public:
    virtual void f() 
    {
        cout<<"cpp: call TestBase f"<get_override("f"))
        {
            f();
            return;
        }
        this->f();
    }
};
class_("TestBase", init<>())
    .def("f", &TestBase::f)
    ;

Python 调用

Python测试代码

TestBase().f()

cpp: call TestBase f

class TestPySub1(TestBase):
    pass
TestPySub1().f()

cpp: call TestBase f

class TestPySub2(TestBase):
    def f(self):
        print "py: call TestPySub2 f"
TestPySub2().f()

py: call TestPySub2 f

结论:

从python层调用 f()

未覆写方法 -> TestBase::f()

已覆写 -> py覆写的 f()


C++ 调用

C++代码:

void test(TestBase* obj)
{
    obj->f_();
}

def("test", &test);

Python测试代码:

test(TestBase())

cpp: call TestBase f_
cpp: call TestBase f

class TestPySub1(TestBase):
    pass
test(TestPySub1())

cpp: call TestBase f_
cpp: call TestBase f

class TestPySub2(TestBase):
    def f(self):
        print "py: call TestPySub2 f"
test(TestPySub2())

cpp: call TestBase f_
py: call TestPySub2 f

结论:

从C++层调用 f()

调用TestBase::f_()

未覆写方法 -> TestBase::f()

已覆写 -> py覆写的 f()

你可能感兴趣的:(基于boost::python,Python中继承C++的类型并覆写虚方法)