确定Python类是抽象基类还是Con

2024-05-14 00:33:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Python应用程序包含许多抽象类和实现。例如:

import abc
import datetime

class MessageDisplay(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractproperty
    def display(self, message):
        pass

class FriendlyMessageDisplay(MessageDisplay):
    def greet(self):
        hour = datetime.datetime.now().timetuple().tm_hour

        if hour < 7:
            raise Exception("Cannot greet while asleep.")
        elif hour < 12:
            self.display("Good morning!")
        elif hour < 18:
            self.display("Good afternoon!")
        elif hour < 20:
            self.display("Good evening!")
        else:
            self.display("Good night.")

class FriendlyMessagePrinter(FriendlyMessageDisplay):
    def display(self, message):
        print(message)

FriendlyMessagePrinter是一个具体的类,我们可以使用它。。。

FriendlyMessagePrinter().greet()
Good night.

…但是MessageDisplayFriendlyMessageDisplay是抽象类,试图实例化一个类将导致错误:

TypeError: Can't instantiate abstract class MessageDisplay with abstract methods say

如何检查给定的类对象是否是(不可实例化的)抽象类?


Tags: selfmessagedatetimedefdisplay抽象类classgood
3条回答
import inspect
print(inspect.isabstract(object))                  # False
print(inspect.isabstract(MessageDisplay))          # True
print(inspect.isabstract(FriendlyMessageDisplay))  # True
print(inspect.isabstract(FriendlyMessagePrinter))  # False

这将检查是否在类对象中设置了内部标志TPFLAGS_IS_ABSTRACT,因此它不会像您的实现那样容易被愚弄:

class Fake:
    __abstractmethods__ = 'bluh'

print(is_abstract(Fake), inspect.isabstract(Fake)) # True, False

抽象类及其具体实现有一个__abstractmethods__属性,其中包含尚未实现的抽象方法和属性的名称。此行为在PEP 3199中描述:

Implementation: The @abstractmethod decorator sets the function attribute __isabstractmethod__ to the value True. The ABCMeta.__new__ method computes the type attribute __abstractmethods__ as the set of all method names that have an __isabstractmethod__ attribute whose value is true. It does this by combining the __abstractmethods__ attributes of the base classes, adding the names of all methods in the new class dict that have a true __isabstractmethod__ attribute, and removing the names of all methods in the new class dict that don't have a true __isabstractmethod__ attribute. If the resulting __abstractmethods__ set is non-empty, the class is considered abstract, and attempts to instantiate it will raise TypeError. (If this were implemented in CPython, an internal flag Py_TPFLAGS_ABSTRACT could be used to speed up this check.)

所以在具体的类中,这个属性要么不存在,要么是一个空集。这很容易检查:

def is_abstract(cls):
    if not hasattr(cls, "__abstractmethods__"):
        return False # an ordinary class
    elif len(cls.__abstractmethods__) == 0:
        return False # a concrete implementation of an abstract class
    else:
        return True # an abstract class

或者更简洁地说:

def is_abstract(cls):
    return bool(getattr(cls, "__abstractmethods__", False))
print(is_abstract(object))                 # False
print(is_abstract(MessageDisplay))         # True
print(is_abstract(FriendlyMessageDisplay)) # True
print(is_abstract(FriendlyMessagePrinter)) # False

您可以使用_ast模块来完成此操作。例如,如果示例代码位于foo.py中,则可以使用"foo.py""FriendlyMessagePrinter"作为参数调用此函数。

def is_abstract(filepath, class_name):
    astnode = compile(open(filename).read(), filename, 'exec', _ast.PyCF_ONLY_AST)
    for node in astnode.body:
        if isinstance(node, _ast.ClassDef) and node.name == class_name:
            for funcdef in node.body:
                if isinstance(funcdef, _ast.FunctionDef):
                    if any(not isinstance(n, _ast.Pass) for n in funcdef.body):
                        return False
            return True
    print 'class %s not found in file %s' %(class_name, filepath)

相关问题 更多 >