如何自定义Python的方法解析顺序mro?

问题描述

我想自定义我的继承方法。

这是示例代码:

class First(object):
    def get(self):
        print('getting from first')

    def set(self):
        print('setting to first')

class Second(object):
    def get(self):
        print('getting from second')

    def set(self):
        print('setting to second')

class Third(First,Second):
    def get(self):
        super(Third,self).get()

    def set(self):
        super(Third,self).set()

现在我想要的行为是这样的:

third = Third()
third.get() # -> should print 'getting from first'
third.set() # -> should print 'setting to second'

现在 mro 显示:

Third.__mro__ ->  (__main__.Third,__main__.First,__main__.Second,object)

我们可以看到 main 中的方法。首先 总是被首先调用。我想要的是那个 main 。在执行 set() 方法期间,第二个被首先调用。

这是我尝试解决的尝试,尝试修改第三类的 MRO

这个想法是交换两个类的两个位置,看看是否可以工作。 首先,一个swap()辅助函数。

def swap(index1,index2,mro_tuple):
    l = list(mro_tuple)
    temp = l[index1]
    l[index1] = l[index2]
    l[index2] = temp
    return tuple(l)

然后在实现set()方法期间,我尝试修改基础类的 mro

class Third(First,self).get()
    def set(self):
        self.__class__.__mro__ = swap(1,2,self.__class__.__mro__) # swap here..
        super(Third,self).set() # then call method**
In [43]: third = Third() 

In [44]: third.get()                                                            
getting from first

In [45]: third.set()                                                            
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-53-c82ac1a0d5bc> in <module>
----> 1 third.set()

<ipython-input-50-00c9baff0d57> in set(self)
      4 
      5     def set(self):
----> 6         self.__class__.__mro__ = swap(1,self.__class__.__mro__) # swap here..
      7         super(Third,self).set() # then call method
      8 

AttributeError: readonly attribute

它表明无法重置__mro__属性。

反正有一种方便的方式实现这种行为吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)