Python unimplemented methods versus abstract methods, which is more pythonic? PyCharm doesn't like methods not implemented in the base class

StackOverflow https://stackoverflow.com/questions/22766798

  •  24-06-2023
  •  | 
  •  

I have a specific problem closely related to PyCharm (Community 3.1.1). The following simple example illustrates this. I will use the screenshot of PyCharm rather than type the code, for reasons that will be clear shortly.

As you can see, the call to self.say_hello() is highlighted in yellow by PyCharm, and presumably this is because say_hello() is not implemented in the Base class. The fact that say_hello() is not implemented in the base class is intentional on my part, because I want a kind of "abstract" effect, so that an instance of Base cannot call say_hello() (and therefore shouldn't call hello()), but that an instance of Child can call hello() (implemented in the Base class). How do I get this "abstract" effect without PyCharm complaining?

As I learned from here, I could use the abc module. But that, to me, would be rather cumbersome and somewhat not pythonic. What are your recommendations?

有帮助吗?

解决方案

I would implement say_hello() as a stub:

class Base(object):
    # ...as above...

    def say_hello(self):
        raise NotImplementedError

Alternatively, put only pass in the body of say_hello().

This would also signal to the user of your Base class that say_hello() should be implemented before she gets an AttributeError when calling obj.hello(). Whether to raise an Exception or to pass depends on whether doing nothing is sensible default behaviour. If you require the user to supply her own method, raise an exception.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top