Breeky
Breeky

Reputation: 61

Python bind method to another instance

I need to merge two methods from different instances of different classes to a single instance of a class.

For example I define two classes:

class A:
    def __init__(self):
        self.name = "a"

    def print_name(self):
        print(self.name)


class B:
    def __init__(self):
        self.name = "b"

    def print_name(self):
        print(self.name)

and then I will try to make another object c and its print_name method must return the results of a.print_name() and b.print_name() so I tried the following :

a = A()
b = B()
c = A()

c.name = "c"
c.print_name_1 = a.print_name
c.print_name_2 = b.print_name
def final_print(self):
    self.print_name_1()
    self.print_name_2()
c.print_name = MethodType(final_print, c)
c.print_name()

Expected output:

c
c

but I get :

a
b

I tried to use types.MethodType as described here but it creates some kind of a method which takes two arguments : the first one will be the 'a' instance and the second one will be the 'c' instance.

Any help to do that properly?

Upvotes: 4

Views: 1369

Answers (1)

Breeky
Breeky

Reputation: 61

I managed to succeed with this, thanks to this answer. I am using the __func__ attribute of a method. So here is the code :

c.name = "c"
c.print_name_1 = MethodType(lambda instance: copy.deepcopy(a.print_name).__func__(instance), c)
c.print_name_2 = MethodType(lambda instance: copy.deepcopy(b.print_name).__func__(instance), c)
def final_print(self):
    self.print_name_1()
    self.print_name_2()
c.print_name = MethodType(final_print, c)
c.print_name()

Upvotes: 1

Related Questions