问题描述
我的Python应用程序包含许多抽象类和实现。例如:
My Python application contains many abstract classes and implementations. For example:
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
is a concrete class that we can use...
FriendlyMessagePrinter().greet()
Good night.
...但是 MessageDisplay
和 FriendlyMessageDisplay
是抽象类,尝试实例化一个类会导致错误:
...but MessageDisplay
and FriendlyMessageDisplay
are abstract classes and attempting to instantiate one would result in an error:
TypeError: Can't instantiate abstract class MessageDisplay with abstract methods say
如何我可以检查给定的类对象是否是(不可实例化的)抽象类?
How can I check if a given class object is an (uninstantiatable) abstract class?
推荐答案
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
是在类对象中设置的,因此无法像您的实现那样容易地对其进行欺骗:
This checks that the internal flag TPFLAGS_IS_ABSTRACT
is set in the class object, so it can't be fooled as easily as your implementation:
class Fake:
__abstractmethods__ = 'bluh'
print(is_abstract(Fake), inspect.isabstract(Fake)) # True, False
这篇关于确定Python类是Abstract基类还是Concrete类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!