Skip to main content
 首页 » 编程设计

python之从 Python 中的常用函数中提取混入

2025年05月04日8cyq1162

考虑两个类,每个类都有一个现有的共享函数,但继承路径不同:

class ClazzA(SuperClazzX): 
    def foo(self): 
        return goo(super(SuperClazzX, self).foo()) 
 
class ClazzB(SuperClazzY): 
    def foo(self): 
        return goo(super(SuperClazzY, self).foo()) 

foo 显然是一个可以提取到 mixin 的通用函数,这样做的正确方法是什么,这样即使一个不同的 super foo 功能仍然存在> 是要被调用吗?

编辑:我删除了另一个 mixin,它令人困惑且无关紧要。

请您参考如下方法:

编辑:更简单的代码

Mixin 可以访问( future )子类的其他基类,这里 C::Mixin::foo 可以访问 C 的其他基类,即 C::Base::foo。 Authoritative explanation here .

class Base(object):  # must be new-style class in py 2.x 
    def foo(self): 
        print "base foo called" 
 
class Mixin(object): 
    def foo(self): 
        rv = super(Mixin, self).foo()  # call actual implementation 
        # use rv 
 
class C(Mixin, Base): 
    pass 
 
C().foo() 
base foo called 

这是做什么的:

  • self是C的实例,它的__mro__是(Mixin, Base)
  • 当Mixin调用super(Mixin, self)时,生成的对象保留基数(Base,)
  • 当 .foo 属性被解析时,这个对象在 Base 中找到它
  • 因此 Base.foo 被原始的 self 调用

如果您想要对实现进行自定义控制,您可以访问自己的基础,例如:

class Foo(...): 
    def foo(self): 
        print self.__class__.__bases__ 

你的 mixin 可能看起来像这样, super 手动的方法:

class Mixin(object): 
    def foo(self): 
        assert self.__class__ is not Mixin  # no point calling directly 
        # find the other base 
        other = [b for b in self.__class__.__bases__ if b is not Mixin] 
        # what to do if there's more than 1 real base? 
        # pick base explicitly 
        base = other[1] 
        # call it,  
        return something(base.foo(self, some_args))