我有一个函数的版本1,如:
def f(a,b,c):
#Some processing
return some_result
Run Code Online (Sandbox Code Playgroud)
后来,我将其升级到版本2.
def f(a,b,c):
#Some processing
#Some more processing
return some_result, additional_result
Run Code Online (Sandbox Code Playgroud)
后一版本返回一个元组.因此,使用版本1的所有客户端代码都已过时.我可以additional_result 按需求吗?
这就是你additional_result当你问它,而你继续只得到some_result仿佛什么都没有改变.
我想到的一个技巧:
def f(a,b,c, need_additional = False):
#Some processing
#Some more processing
if not need_addional:
return some_result
else:
return some_result, additional_result
Run Code Online (Sandbox Code Playgroud)
还有什么更好的?还是更通用的?
我认为更优雅的解决方案是让您的旧功能成为新功能的传统包装器:
def f(a,b,c):
some_result, additional_result = f_new(a,b,c)
return some_result
def f_new(a,b,c):
#Some processing
#Some more processing
return some_result, additional_result
Run Code Online (Sandbox Code Playgroud)
我不得不承认我主要使用你建议的模式,而不是我的:),但是向后兼容的默认参数并不是很好的练习.
我最终将其实现为:
def f(a,b,c, v2 = False):
#Some processing
#Some more processing
if not v2:
return some_result
else:
v2_dict = {}
v2_dict['additional_result'] = additional_result
v2_dict['...'] = ...
return some_result, v2_dict
Run Code Online (Sandbox Code Playgroud)
优点:
| 归档时间: |
|
| 查看次数: |
191 次 |
| 最近记录: |