gpt4 book ai didi

Python - 在调用继承方法时创建附加语句

转载 作者:太空宇宙 更新时间:2023-11-03 14:58:22 25 4
gpt4 key购买 nike

假设我有这个:

class Foo:
...
def func():
return 1+2

class Bar(Foo):
...
def another_func():
# additional stuff I want to do when my parent's func() is called

我不想覆盖 func ,但我确实想在它被调用时添加一些额外的语句。另外,我不想更改原始的 Foo.func

有可能吗?如果没有,是否有解决方法?

最佳答案

没有办法做到这一点,规范的解决方案是覆盖 func 并像 sop 一样包装原始函数>

class Bar(Foo):
...
def func():
# additional stuff I want to do when my parent's func() is called
res = super(Bar, self).func() # super().func() on Py3
# additional stuff I want to do after my parent's func() is called
return res

关于Python - 在调用继承方法时创建附加语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40695382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com