0

In python 3, is there a way to assign a function to a method of an instance (if I may say so)? I'm not talking about class method overriding

for example :

class MyClass:
    def __init__(self, a): 
        self.a=a
        self.b=0

    def set_b(self):
        pass


def fun(x):
    print(x)
    x.b=2*x.a

my=MyClass(2)
my.set_b=fun

my.set_b
print(my.b)

The output is 0. I would like it to be 4. I'm not very experienced and I think I don't have the right approach. I wanted to set set_b dynamically.

Edit

I corrected the line :

my.set_b

to :

my.set_b()

and I get the error:

Traceback (most recent call last): File "test.py", line 20, in my.set_b() TypeError: fun() missing 1 required positional argument: 'x'

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
bim
  • 3
  • 2
  • Your construction is very awkward: my.set_b requires an argument (an instance of MyClass) because fun(x) requires such an argument. So you're passing a class instance to a class method. I don't think that's what you want to do. Unfortunately, I am not able to tell you what a working solution would be. – Peter M. Oct 01 '20 at 19:58
  • You can't "assign to a method". You assign *to names/attributes*. – juanpa.arrivillaga Oct 02 '20 at 07:35
  • thanks @juanpa.arrivillaga – bim Oct 02 '20 at 10:06

2 Answers2

0

This works (but not by replacing the class method by a function that's defined outside the class):

class MyClass:
    def __init__(self, a): 
        self.a=a
        self.b=0

    def set_b(self):
        self.a, self.b = fun(self.a, self.b)

def fun(a,b):
    b=2*a
    return a,b


my=MyClass(2)
my.set_b()
print(my.b)
Peter M.
  • 124
  • 9
  • Yeah. This is what I do (though it doesn't feel so nice to me): def set_b(self): self.set_b=set_b(self) def set_b(x): x.b=2*x.a Thanks for your time – bim Oct 02 '20 at 07:47
0

You can use my (instance of MyClass) as argument to your method set_b() and you will have the result you are looking for :

class MyClass:
    def __init__(self, a): 
        self.a=a
        self.b=0

    def set_b(self):
        pass


def fun(x):
    print(x)
    x.b=2*x.a

my=MyClass(2)
my.set_b=fun

my.set_b(my)
print(my.b)
Pierre-Loic
  • 1,524
  • 1
  • 6
  • 12