【发布时间】:2020-10-02 18:50:16
【问题描述】:
我有一个继承自ABC 的类,并且没有任何abstractmethod。
我想检查它是否是一个抽象类,并且目前被难住了。
Determine if a Python class is an Abstract Base Class or Concrete 规定使用inspect.isabstract。但是,这仅在使用 abstractmethod 时才有效。
如何检测一个类是否直接从ABC 继承,而不使用inspect.isabstract?
测试用例
# I need this to be flagged as abstract
class AbstractBaseClassNoAbsMethod(ABC):
pass
# This is currently flaggable with `inspect.isabstract`
class AbstractBaseClassWithAbsMethod(ABC):
@abstractmethod
def some_method(self):
"""Abstract method."""
# I need this to be flagged as not abstract
class ChildClassFromNoAbsMethod(AbstractBaseClassNoAbsMethod):
pass
我考虑过使用issubclass(some_class, ABC),但这是True,即使是上面的ChildClassFromNoAbsMethod。
当前最佳解决方案
我目前的最佳解决方案使用__bases__。这基本上只是列出父类,见How to get the parents of a Python class?
def my_isabstract(obj) -> bool:
"""Get if ABC is in the object's __bases__ attribute."""
try:
return ABC in obj.__bases__
except AttributeError:
return False
这是一个可行的解决方案。我不确定是否有更好/更标准的方法。
【问题讨论】:
标签: python oop abc abstract-methods