gpt4 book ai didi

python - 从 C++ 转换为 Python - 如何在 Python 中声明没有定义的虚方法

转载 作者:行者123 更新时间:2023-11-30 01:35:13 25 4
gpt4 key购买 nike

我正在尝试将 C++ 库转换为 Python。

C++文件

class A
{
public:
virtual void example(paramtype, paramtype) = 0;
void myMethod(void);
}

void A::myMethod(void){
example();
}

class B: public A
{
public:
void example(paramtype p1, paramtype p2); // implemented
}

我在实现 myMethod 时遇到困难。我想创建一个变量来保存示例方法并调用 myMethod 中的变量,如下所示。

python 文件

class A:
def __init__(self):
self.example = None

def myMethod(self):
self.example()

但是后来编辑说不能调用 None 类型(当然)。我怎样才能做到这一点?

最佳答案

C++ 中的基类声明了一个没有定义的虚方法。

virtual void example(paramtype, paramtype) = 0;

这意味着它必须在要使用的子类中定义。在您的库中,它是 B 类。

在Python中,你可以使用

raise NotImplementedError()

表示一个方法还没有被实现。参见 this answer了解更多详情。

class A:
def example(self):
raise NotImplementedError()

def myMethod(self):
self.example()

class B(A):
# override the example method by providing the implementation
def example(self):
# implementation

在这个例子中,在类型为A 的对象上调用example 会抛出一个错误,因为方法没有定义。您只能在 B 类型的对象上调用该方法。

关于python - 从 C++ 转换为 Python - 如何在 Python 中声明没有定义的虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54589974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com