小编wei*_*ang的帖子

虚拟子类的用途是什么?

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)

python metaclass subclass python-2.x

4
推荐指数
1
解决办法
849
查看次数

标签 统计

metaclass ×1

python ×1

python-2.x ×1

subclass ×1