Inyoung Kim 김인영
Inyoung Kim 김인영

Reputation: 1597

Converting from c++ to python - How to declare a virtual method with no definition in python

I'm trying to convert a c++ library to python.

c++ file

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
}

I am having hard time with implementation of myMethod. I thought of making a variable to hold the example method and invoke the variable in myMethod like below.

python file

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

    def myMethod(self):
        self.example()

But then editor says None type can't be called(of course). How can I achieve this?

Upvotes: 1

Views: 358

Answers (2)

anlew
anlew

Reputation: 174

To convert your C++ code into python3, you should derive from python's abstract base class (ABC). This lets you create abstract methods:

from abc import ABC, abstractmethod


class A(ABC):
    def __init__(self):
        pass

    @abstractmethod
    def example(self, a, b):
        raise NotImplementedError

    def my_method(self):
        self.example(1, 2)

Additional information can be found here https://docs.python.org/3/library/abc.html

Upvotes: 2

Arc676
Arc676

Reputation: 4465

The base class in C++ is declaring a virtual method with no definition.

virtual void example(paramtype, paramtype) = 0;

That means it must be defined in a child class to be used. In your library, that's class B.

In Python, you can use

raise NotImplementedError()

to indicate that a method has not been implemented. See this answer for more details.

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

In this example, calling example on an object of type A will throw an error, because the method isn't defined. You can only invoke the method on an object of type B.

Upvotes: 3

Related Questions