在 python 中,我想通过组合来模拟以下行为:
class Object1(object):
def __init__(self):
pass
def method1(self):
print "This is method 1 from object 1"
return self.method2()
def method2(self):
raise Exception
class Object2(Object1):
def method2(self):
print "This is method 2 from object 2"
obj2 = Object2()
obj2.method1()
输出是:
This is method 1 from object 1
This is method 2 from object 2
换句话说,我希望能够创建一个类来复制现有类的行为,但某些方法除外。但是,重要的是,一旦我的程序进入现有类的方法,它就会返回到新类,以防我覆盖了该函数。但是,对于以下代码,情况并非如此:
class Object3(object):
def __init__(self):
pass
def method1(self):
print "This is method 1 from object 3"
return self.method2()
def method2(self):
raise Exception
class Object4(object):
def __init__(self):
self.obj = Object3()
def __getattr__(self, attr):
return getattr(self.obj, attr)
def method2(self):
print "This is method 2 from object 4"
obj4 = Object4()
obj4.method1()
不是从 Object3 的 method1 调用来自 Object4 的 method2(我想要的行为),而是调用来自 Object3 的 method2(并引发异常)。有什么方法可以在不更改 Object3 的情况下实现我想要的行为?