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)
Run Code Online (Sandbox Code Playgroud)
输出:
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 …Run Code Online (Sandbox Code Playgroud)