Can I exactly mimic inheritance behavior with delegation by composition in Python?

你说的曾经没有我的故事 提交于 2019-12-12 05:22:04

问题


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()

The output is:

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()

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?


回答1:


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.



来源:https://stackoverflow.com/questions/44902864/can-i-exactly-mimic-inheritance-behavior-with-delegation-by-composition-in-pytho

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!