python - 使用 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")
有没有可能的方法来做到这一点?编辑:谢谢大家的回答!对我来说重要的是,我真的可以重载,而不仅仅是替换现有的方法。我改变了我的例子来反映这一点!
干杯!
解决方案
class foo():
def hello(self, baa=""):
print("hello"+str(baa))
def main():
test = foo()
test.hello()
test.hello("bye")
将输出
hello
hellobye
推荐阅读
- docker - GitHub Actions Docker 构建和推送无法复制:意外状态:413 请求实体太大
- javascript - for 循环仅显示数组对象中的一项和最后一项
- r - 基于多个条件创建新变量
- javascript - 如何使用点积找出旋转角度
- javascript - 如何在反应中嵌套条件语句 - 变得未定义
- google-visualization - 谷歌可视化 - 选择处理程序不起作用
- report - 在 AdSense v2 中接收报告数据
- gradle - Gradle 守护进程类加载器
- php - 如何在我的页面上显示我教父的名字
- java - 将 MutableList 或 ArrayList 从 Activity A 传递和检索到 B