0

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?

Charlee
  • 23
  • 4

1 Answers1

0

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.

Artsiom Vahin
  • 51
  • 1
  • 7
  • I don't think this is what I'm looking for. The problem is that the parent class can vary, so inheritance is not an option. – Charlee Jul 04 '17 at 10:30
  • @Charlee , in that case the solution I see is altering Object3. Have method1 in Onject3 take a reference `def method1(self, ref): print "This is method 1 from object 3" return ref.method2()` Then call them like so: `obj4 = Object4() obj4.method1(obj4) ` EDIT: the formatting is messed up, sorry – Artsiom Vahin Jul 04 '17 at 10:47
  • Unfortunately I can't do this :( seeing that method2 does actually exist in Object3 already, and in some cases will be used like this. If I change how method2 is called I mess up the existing code. It's ok if it is not possible, I think I've got another solution, I was mainly curious if this was possible, and so far it seems like this is not the case. – Charlee Jul 04 '17 at 10:54
  • @Charlee sorry to hear, best of luck with your other solution :) – Artsiom Vahin Jul 04 '17 at 11:47