2012-11-25 97 views
4

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

class Base(object): 
    '...' 

class One(Base) 
    '...' 

class Two(Base) 
    '...' 

...我沃尔德想进行修改,Base没有实际修改上面的代码。也许是这样的:

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

import third_party_code 

# ...my own code 

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

+1

你心里有什么改变? – NPE

+0

'Base'有一些需要修改的子类使用的方法。 –

+1

应该可以在'Base.method = new_method'这样的东西中进行猴子补丁,这将在子类的实例中正确解析。 – joeln

回答

5

也许你可以把这些方法猴子打成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() 

此打印出

original foo 
original foo 
monkey-patched foo 
monkey-patched foo