首页 > 解决方案 > 使用 setattr() 重载已经存在的类定义中的方法

问题描述

我想知道是否可以向现有类添加方法,重载现有方法。我知道,我可以使用 setattr() 将函数添加到类中,但是重载不起作用。

作为一个例子,我想添加到类

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

以下函数,重载“hello”

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

很明显,这行得通

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

但我希望能够这样称呼它

test.hello("bye")

有没有可能的方法来做到这一点?编辑:谢谢大家的回答!对我来说重要的是,我真的可以重载,而不仅仅是替换现有的方法。我改变了我的例子来反映这一点!

干杯!

标签: pythonoverloading

解决方案


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


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

将输出

hello hellobye


推荐阅读