我的 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.
...但是MessageDisplay
andFriendlyMessageDisplay
是抽象类,尝试实例化一个会导致错误:
TypeError: Can't instantiate abstract class MessageDisplay with abstract methods say
如何检查给定的类对象是否是(不可实例化的)抽象类?