Python:覆盖基类

Cap*_*day 6 python inheritance

我正在考虑修改某些第三方Python代码的行为.有许多类派生自基类,为了轻松实现我的目标,最简单的方法就是覆盖用于派生所有其他类的基类.有没有一个简单的方法来做到这一点,而无需触及任何第三方代码?如果我没有清楚地解释这个:

class Base(object):
    '...'

class One(Base)
    '...'

class Two(Base)
    '...'
Run Code Online (Sandbox Code Playgroud)

...我希望在Base 实际修改上述代码的情况下进行修改.也许是这样的:

# ...code to modify Base somehow...

import third_party_code

# ...my own code
Run Code Online (Sandbox Code Playgroud)

Python可能有一些可爱的内置解决方案来解决这个问题,但我还没有意识到这一点.

NPE*_*NPE 7

也许你可以将这些方法用于修补Base

#---- This is the third-party module ----#

class Base(object):
  def foo(self):
    print 'original foo'

class One(Base):
  def bar(self):
    self.foo()

class Two(Base):
  def bar(self):
    self.foo()

#---- This is your module ----#

# Test the original
One().bar()
Two().bar()

# Monkey-patch and test
def Base_foo(self):
  print 'monkey-patched foo'

Base.foo = Base_foo

One().bar()
Two().bar()
Run Code Online (Sandbox Code Playgroud)

打印出来

original foo
original foo
monkey-patched foo
monkey-patched foo
Run Code Online (Sandbox Code Playgroud)