python - 在 Python 中调用函数之前检查函数是否引发 NotImplementedError

标签 python python-3.x class oop

我有以下简化方案:

class NetworkAnalyzer(object):
    def __init__(self):
       print('is _score_funct implemented?')

    @staticmethod
    def _score_funct(network):
        raise NotImplementedError

class LS(NetworkAnalyzer):
    @staticmethod
    def _score_funct(network):
        return network

我正在寻找我应该使用什么来代替 print('is _score_funct implemented?') 以确定子类是否已经实现了 _score_funct(network) 或不。

注意:如果有更 pythonic/常规的代码结构方式,我也将不胜感激。我这样定义它的原因是,一些 NetworkAnalyzer 子类在它们的定义中有 _score_funct,而没有它的子类将有不同的变量初始化,尽管它们具有相同的结构

最佳答案

使用抽象基类,除非它实现了所有抽象方法,否则您将无法实例化该类:

import abc

class NetworkAnalyzerInterface(abc.ABC):
    @staticmethod
    @abc.abstractmethod
    def _score_funct(network):
        pass

class NetworkAnalyzer(NetworkAnalyzerInterface):
    def __init__(self):
        pass

class LS(NetworkAnalyzer):
    @staticmethod
    def _score_funct(network):
        return network

class Bad(NetworkAnalyzer):
    pass

ls = LS()   # Ok
b = Bad()   # raises TypeError: Can't instantiate abstract class Bad with abstract methods _score_funct

关于python - 在 Python 中调用函数之前检查函数是否引发 NotImplementedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49903165/

相关文章:

python - 如何从 main 引用嵌套在类中的定义变量

java - 如何使用参数在 Java 中创建实例的方法?

python - 是否可以将 tqdm 用于不是循环的进程?

python - 如何使使用 Discord.py 机器人登录的帐户加入特定服务器

java - 如何知道 .jar 文件中的哪些类被引用了?

python-3.x - 如何从 PIL 中的 ImageDraw 获取图像?

python - pip3 没有安装 python3 的包

python - Flask HTML 转义装饰器

python 观察者模式

android - 是否可以在 Python 3 上为 Android 构建 Kivy 应用程序?