我可以使用Python中的组成通过委托来精确模仿继承行为吗? [英] Can I exactly mimic inheritance behavior with delegation by composition in Python?

查看:101
本文介绍了我可以使用Python中的组成通过委托来精确模仿继承行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,我想通过组合来模仿以下行为:

In python, I want to mimic the following behavior with delegation by composition:

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

换句话说,我希望能够创建一个类,该类复制某些方法之外的现有类的行为.但是,重要的是,一旦我的程序进入了已经存在的类的方法中,万一我覆盖了该函数,它就会返回到新的类.但是,对于以下代码,情况并非如此:

In other words, I want to be able to create a class that copies the behavior of an already existing class except for certain methods. However, it is important that once my program goes into a method of the already existing class, it returns to the new class in case I have overridden the function. However, with the following code this is not the case:

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的情况下,有什么方法可以实现我想要的行为?

Instead of method2 from Object4 being called from method1 of Object3 (the behavior I want), method2 from Object3 is called (and an exception is raised). Is there any way to achieve the behavior I want without making changes to Object3?

推荐答案

由于没有对Object3类可用的Object4实例(obj4)的引用,它将调用self的method2,即Object3.

Since there is no reference to Object4 instance (obj4) available to Object3 class, it will be calling method2 of self, i.e. Object3.

此答案可能会提供更多信息明确性和可能的​​解决方案.

This answer might provide more clarity and a possible solution.

这篇关于我可以使用Python中的组成通过委托来精确模仿继承行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆