如何在 python 中实际使用 NotImplementedError?
How to actually use the NotImplementedError in python?
我目前有一个基地 class 像这样:
from abc import ABC, abstractmethod
class BaseClass(ABC):
@abstractmethod
def __init__(self, param1, param2):
self._param1 = param1
self._param2 = param2
@abstractmethod
def foo(self):
raise NotImplementedError("This needs to be implemented")
现在我有了希望用户覆盖的抽象方法 foo。因此,如果他们这样定义 class:
from BaseClassFile import BaseClass
class DerrivedClass(BaseClass):
def __init__(self, param1, param2):
super().__init__(param1, param2)
所以这里方法 foo 没有被覆盖/在 DerrivedClass 中定义,当我创建一个这种类型的对象时,它抛出一个 TypeError 但我想抛出一个 NotImplementedError。我该怎么做。
当前错误:
TypeError: Can't instantiate abstract class FF_Node with abstract methods forward
问题是,你的错误
TypeError: Can't instantiate abstract class FF_Node with abstract methods forward
被抛出的那一刻,你的实例就创建好了。当一个方法被声明为 @abstractmethod
时,它必须在 classes 中有一个覆盖方法继承这个父 class。否则 python 将在子 class 的实例创建后立即抛出错误。
如果你想让你的代码抛出一个 NotImplementedError
你需要删除 @abstactmethod
装饰器。
无法调用抽象方法。 raise NotImplementedError()
行不可能作为日志到达,因为它是 @abstactmethod
.
我目前有一个基地 class 像这样:
from abc import ABC, abstractmethod
class BaseClass(ABC):
@abstractmethod
def __init__(self, param1, param2):
self._param1 = param1
self._param2 = param2
@abstractmethod
def foo(self):
raise NotImplementedError("This needs to be implemented")
现在我有了希望用户覆盖的抽象方法 foo。因此,如果他们这样定义 class:
from BaseClassFile import BaseClass
class DerrivedClass(BaseClass):
def __init__(self, param1, param2):
super().__init__(param1, param2)
所以这里方法 foo 没有被覆盖/在 DerrivedClass 中定义,当我创建一个这种类型的对象时,它抛出一个 TypeError 但我想抛出一个 NotImplementedError。我该怎么做。
当前错误:
TypeError: Can't instantiate abstract class FF_Node with abstract methods forward
问题是,你的错误
TypeError: Can't instantiate abstract class FF_Node with abstract methods forward
被抛出的那一刻,你的实例就创建好了。当一个方法被声明为 @abstractmethod
时,它必须在 classes 中有一个覆盖方法继承这个父 class。否则 python 将在子 class 的实例创建后立即抛出错误。
如果你想让你的代码抛出一个 NotImplementedError
你需要删除 @abstactmethod
装饰器。
无法调用抽象方法。 raise NotImplementedError()
行不可能作为日志到达,因为它是 @abstactmethod
.