为了简单起见,我有一个旧类 cal1
,其方法为 defcalculate(self,a,b,c,d,e)
并且有很多地方可以使用调用此方法,例如:ans=cal1.calculate(a,b,c,d,e)
。
现在我有一个新类 cal2
,它应该用与 cal1
重用相同名称的所有方法来替换旧类,但新类只需要更少的参数 c, d,e defcalculate(self,c,d,e)
而不是 a,b。
问题:有没有办法将新方法 calculate(self,c,d,e)
改造为旧代码,而不更改旧代码中的每一行(例如:保留 ans=cal.calculate(self,a,b,c,d,e)
)?
我知道的唯一方法是更改新方法以将 a 和 b 作为虚拟值, calculate(dummy_a, dummy_b, c, d, e)
,但对于将来的代码,我需要携带 dummy_a
,dummy_b
。
最佳答案
如果您通过关键字指定参数(例如 c="value", d="value", e="value"
,那么干净利落就好了.
使用位置参数,您可以仅捕获和解压您想要的项目。
旧的计算函数签名
def calculate(self, a, b, c, d, e):
...
新的计算方法签名(带有关键字参数):
You can use the
**kwargs
to capture all unnecessary arguments here.
def calculate(self, c, d, e, **kwargs):
...
新的计算方法签名(带有位置参数):
You can use the
*args
to capture all arguments and pull out the ones you want.
def calculate(self, *args):
*unnecessary, c, d, e = args
...
关于python - 用更少的参数重写方法 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60963276/