我想知道是否可以向现有类中添加方法,从而使现有方法过载。我知道,我可以使用setattr()将函数添加到类中,但是重载不起作用。
作为示例,我想添加到该类中
class foo:
def hello(self):
print("hello")
下面的函数,重载“你好”
def hello2(baa):
print("hello"+str(baa))
很明显,这有效
setattr(foo,"hello2",hello2)
test = foo()
test.hello()
test.hello2("bye")
但我想可以这样称呼它
test.hello("bye")
有没有办法做到这一点? 干杯!
将输出
hello hellobye
You can actually avoid using
setattr
here. Since you know the method you want to overload ahead of time, you can do:其次是;