the.polo
the.polo

Reputation: 377

Using setattr() to overload a method in an already existing class definition

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!

Upvotes: 0

Views: 185

Answers (2)

Mario Ishac
Mario Ishac

Reputation: 5877

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()

Upvotes: 2

Gal
Gal

Reputation: 504

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


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

will output

hello hellobye

Upvotes: 2

Related Questions