[英]What is the efficient way to write code where argument with same value is passed to a function that is called multiple times ? (python)
[英]What is a good way in python to reduce code repetition when a function with many parameters is called multiple times?
我们在近距离的多个地方使用了以下函数调用:
func(param1, param2, param3, param4, param5)
我想用
funccall()
在所有的地方。
有宏的概念吗? 给出所有参数的部分(标记答案正确)是正确的,如果所有后续调用都在同一范围内,则它可以正常工作。
如果场景如下所示:
A():
func(p1,p2,p3,p4,p5) # 3 times
B():
func(p1,p2,p3,p4,p5) # 2 times
C():
func(p1,p2,p3,p4,p5) # 4 times
使用部分:
A():
funccall = partial(func,p1,p2,p3,p4,p5)
funccall() # 3 times
B():
funccall = partial(func,p1,p2,p3,p4,p5)
funccall() # 2 times
C():
funccall = partial(func,p1,p2,p3,p4,p5)
funccall() # 4 times
理想(如果代码遵循惯例并且可读性不是问题)
macro funccall() = func(p1,p2,p3,p4,p5)
A():
funccall() # 3 times
B():
funccall() # 2 times
C():
funccall() # 4 times
设置默认参数,只用那些与默认参数不同的参数明确调用函数!
例如def func(param1=0, param2="abc", param3=0.3)
用于定义
调用时result = func(param1=3)
。
(未经测试,但我认为没有理由不这样做!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.