1

Say I have two functions

def do1(x, y):
    return x + y

def do2(x, y):
    return x - y

I can create a class like this

class foo(object):
    def __init__(self, func):
        self.func = func

abc = foo(func=do1)
abc.func(1, 1)  # return 2
abc = foo(func=do2)
abc.func(1, 1)  # return 0

Is it possible for me make abc.func to be a method rather than an attribute?

Thanks.

pe-perry
  • 2,591
  • 2
  • 22
  • 33

1 Answers1

0

You can add a method to a class like so:

def do(self, x, y):
  return x+y

class Foo(object0:
  def __init(self):
    pass

Foo.bar = do

a = Foo()
a.bar(1,2)
out> 3

Or to an instance:

def do2(x,y):
  return x + y

a = Foo()
a.bar2 = do2
a.bar2(3,4)
out> 7
Bastiaan
  • 4,451
  • 4
  • 22
  • 33