class AnimalMeta(type):
def __instancecheck__(cls, instance):
return cls.__subclasscheck__(type(instance))
def __subclasscheck__(cls, sub):
return (hasattr(sub, 'eat') and callable(sub.eat) and
hasattr(sub, 'sleep') and callable(sub.sleep))
class Animal(object):
__metaclass__ = AnimalMeta
pass
class Dog(object):
def eat(self):
print "eat"
def sleep(self):
print "sleep"
dog = Dog()
dog.eat()
print isinstance(dog, Animal)
print issubclass(dog, Animal)
输出:
eat
True
True
我正在尝试理解Python虚拟子类,如上所示的示例。实例中,虚拟子类不需要实现抽象方法。
虚拟子类的真正用途是什么?在我看来,虚拟子类的作用类似于鸭子类型和对象继承之间的某种东西。
鸭子类型--虚拟子类--对象继承