Skip to content

NotImplementedError

错误信息

                NotImplementedError
              

快速摘要

你 called 方法 or 函数那个是 定义但 不 yet implemented — placeholder 那个需要到 是 filled in.

为什么发生

  • Calling 抽象方法那个 hasn't 是 overridden

  • Using stub or placeholder 函数

  • Calling 方法那个 subclass 是 supposed 到 implement

最小示例

✗ 错误代码
class Animal:
    def speak(self):
        raise NotImplementedError

class Dog(Animal):
    pass  # Forgot to implement speak

Dog().speak()  # NotImplementedError
✓ 修复代码
class Animal:
    def speak(self):
        raise NotImplementedError

class Dog(Animal):
    def speak(self):
        return "Woof!"

print(Dog().speak())  # Woof!

subclass 必须 implement 抽象方法. Dog.speak() 现在返回 'Woof!' 相反的 raising NotImplementedError.

如何诊断

  • 查找方法那个 raised 错误

  • 检查如果它 包含 'raise NotImplementedError'

  • Determine 什么 implementation 是 expected

如何修复

  • Implement 方法 in subclass

  • Provide missing functionality

  • Use ABC (抽象基础类) for proper 抽象方法 enforcement

如何预防

  • Use abc.ABC and @abstractmethod for 抽象方法

  • Document 哪个方法必须是 overridden

  • Implement 所有必需方法之前 using 类

相关资源

相关术语

相关课程

← 返回语言