是否有可能使元类方法参与方法解析?

时间:2016-04-06 07:30:15

标签: python metaclass

考虑这个例子:

class Meta(type):
    def method(*_, **__):
        print('Meta')


class A(object):
    __metaclass__ = Meta


class B(object):
    @classmethod
    def method(*_, **__):
        print('B')


class C(A, B):
    pass


C.method() # prints 'B'

我们在这里有一个类A,其中包含方法method,在其元类Meta中定义。我们有一个类B,它也有一个方法method,但定义为一个类方法。

C,继承自AB,结果中有method来自B类。

但如果Amethod定义为类方法,则C已从method继承A

我想找到一种方法让Meta.method参与继承,好像它是一个使用这个元类的类的类方法。有可能吗?

1 个答案:

答案 0 :(得分:1)

如果查找对象本身的属性失败,则只查找类型上的方法;将此与实例属性与类属性进行比较;这是一样的。

如果您需要一种参与MRO的方法,请将其放在课程本身上。元类可以这样做:

class Meta(type):
    def __new__(mcls, name, bases, body):
        cls = super(Meta, mcls).__new__(mcls, name, bases, body)
        if not hasattr(cls, 'method'):
            @classmethod
            def method(*_, **__):
                print('Meta')
            cls.method = method
        return cls

只有在没有这样的方法时,才会将方法粘贴在新创建的类上;这允许您的类(或任何子类)覆盖元类提供的方法,并防止任何子类在可以继承的地方获得相同的内容。

相关问题