0

I was wondering if it is possible to add a method to an existing class, overloading an already existing method. I know, that I can use setattr() to add a function to a class, however overloading does not work.

As an example I would like to add to the class

class foo:
    def hello(self):
        print("hello")

The following function, overloading "hello"

def hello2(self,baa):
    self.hello()
    print(str(baa))

it is clear that this works

setattr(foo,"hello2",hello2)    
test = foo()
test.hello()
test.hello2("bye")

but I would like to be able to call it like this

test.hello("bye")

Is there a possible way to do this? EDIT: Thank you all for your answers! It is important to me, that I can really overload, and not only replace the existing method. I changed my example to reflect that!

Cheers!

the.polo
  • 347
  • 3
  • 11
  • 2
    Does this answer your question? [Can I override a class function without creating a new class in Python?](https://stackoverflow.com/questions/17757238/can-i-override-a-class-function-without-creating-a-new-class-in-python) – Georgy May 09 '20 at 12:27
  • hmm not directly I am afraid, but i might just use inheritance to solve the issue, thank you for the hint! – the.polo May 09 '20 at 18:17

2 Answers2

2
class foo():
    def hello(self, baa=""):
        print("hello"+str(baa))


def main():
     test = foo()
     test.hello()
     test.hello("bye")

will output

hello hellobye

Gal
  • 504
  • 4
  • 11
2

You can actually avoid using setattr here. Since you know the method you want to overload ahead of time, you can do:

def hello2(self, baa):
    print("hello"+str(baa))

followed by;

foo.hello = hello2
test = foo()
test.hello()
Mario Ishac
  • 5,060
  • 3
  • 21
  • 52