Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

python - What should I put in the body of an abstract method?

Say I have the following abstract class Foo:

import abc

class Foo(abc.ABC):

    @abc.abstractmethod
    def bar(self):
        raise NotImplementedError

What should I put in the body of the bar method?

I see a lot of code that has raise NotImplementedError, as shown above. However, this seems redundant, since any subclass that does not implement bar will raise the TypeError: Can't instantiate abstract class Foo with abstract methods bar when it is instantiated.

Is it Pythonic to leave bar empty, as follows:

import abc

class Foo(abc.ABC):

    @abc.abstractmethod
    def bar(self):
        ...

This is what is done in the Python docs for Abstract Base Classes, but I'm not sure if that's just a placeholder or an actual example of how to write code.

If it's ok to leave bar with only three dots (...), when should I use NotImplementedError?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The documentation does aim to give you an example. You don't have to follow it.

You could provide a default; subclasses are still free to use super() to call your implementation. This is what most of the collections.abc classes do; see the source code.

Size for example, returns 0 for __len__:

class Sized(metaclass=ABCMeta):
    # ...
    @abstractmethod
    def __len__(self):
        return 0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...