【发布时间】:2020-05-09 12:08:13
【问题描述】:
我想知道是否可以向现有类添加方法,重载现有方法。我知道,我可以使用 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")
有没有可能的方法来做到这一点? 编辑:谢谢大家的回答!对我来说重要的是,我真的可以重载,而不仅仅是替换现有的方法。我改变了我的例子来反映这一点!
干杯!
【问题讨论】:
-
hmm 恐怕不是直接的,但我可能只是使用继承来解决问题,谢谢您的提示!
标签: python overloading