从Python中的一个公共函数中提取mixin

2024-09-19 23:28:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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,它是混乱和无关的。在


Tags: 方法函数self路径returnfoodefmixin
1条回答
网友
1楼 · 发布于 2024-09-19 23:28:51

编辑:更简单的代码

Mixin可以访问(future)子类的其他基,这里C::Mixin::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

它的作用是:

  • selfC的实例,它的{}是(Mixin,Base)
  • 当Mixin调用super(Mixin, self)时,结果对象将保留bases(Base,)
  • 解析.foo属性时,此对象在Base中找到它
  • 因此,Base.foo是用原始的self调用的

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

^{pr2}$

你的mixin可以看起来像这样,超级手动方式:

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))

相关问题 更多 >