【问题标题】:How to override systematically and transparently Python methods如何系统地和透明地覆盖 Python 方法
【发布时间】:2011-01-19 12:42:55
【问题描述】:

我正在寻找一种“简单”的解决方案来系统地覆盖 Python (=>2.6) 中的一些继承方法。根据我之前的问题here,我会想出一个解决方案:

def override(cls, o):
"""Override class method(s)."""
for t in o: # possible problem; nondeterministic order
    for name in o[t]:
        mtbo= getattr(cls, name).im_func
        om= t(mtbo)
        om.__name__= mtbo.__name__
        om.__doc__= mtbo.__doc__
        # What additional magic is needed here to act as 'genuine' method of super class?
        setattr(cls, name, om)

if __name__== '__main__':
    class B(object):
        def f1(self, val):
            """Doc of B.f1"""; print '1: ', val
        def f2(self, val):
            """Doc of B.f2"""; print '2: ', val
    class A(B):
        pass

    def t(f, msg):
        def g(self, *args, **kwargs):
            print msg, ' entering'; result= f(self, *args, **kwargs)
        return g
    t1= lambda f: t(f, 't1'); t2= lambda f: t(f, 't2')
    override(A, {t1: ['f1', 'f2'], t2: ['f2']})

    def tst(c):
        c.f1(1); print c.f1.__name__, c.f1.__doc__
        c.f2(2); print c.f2.__name__, c.f2.__doc__
    tst(B()), tst(A())

这似乎对我(当前)的目的来说足够好。但是我希望能够尽可能透明地覆盖,因此我将保留超类方法名称和文档。现在我的具体问题是:我应该保留其他任何东西吗?您对此有何解决方案?

更新: 我认为现在这个问题有更广泛的影响:我想我应该问(最初)如何装饰方法,或者函数足够合理的 Pythonic 方式。

【问题讨论】:

  • 你能提供一个真实的例子来说明你想在哪里做这件事 - 我有一种唠叨的感觉,你是出于错误的原因绕过继承,如果你能把问题框定出来的话会有帮助的。

标签: python inheritance overriding transform


【解决方案1】:

您无需手动分配__name____doc__ 以及可能的其他人,您可能只需调用functools.update_wrapper 以确保复制相关属性。

【讨论】:

  • 终于有人知道我的意图了。即使我浏览了很多文档,但实际上我还是第一次遇到“update_wrapper”。我现在将更详细地研究它。我现在也意识到这是一个比“覆盖类方法”更普遍的问题。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
  • 2012-09-06
  • 2012-06-23
  • 1970-01-01
相关资源
最近更新 更多