我有一个向远程API发出请求的类。我希望能够减少我正在拨打的电话数量。我班的一些方法会进行相同的API调用(但出于不同的原因),所以我想他们能够“共享”一个缓存的API响应。Python - 最好有多种方法或大量的可选参数?
我不完全确定是否Pythonic使用可选参数或使用多个方法,因为如果方法在进行API调用时具有一些必需的参数。
下面是我看到他们的认同,你认为哪个最好?
class A:
def a_method(item_id, cached_item_api_response = None):
""" Seems awkward having to supplied item_id even
if cached_item_api_response is given
"""
api_response = None
if cached_item_api_response:
api_response = cached_item_api_response
else:
api_response = ... # make api call using item_id
... #do stuff
或者这样:
class B:
def a_method(item_id = None, cached_api_response = None):
""" Seems awkward as it makes no sense NOT to supply EITHER
item_id or cached_api_response
"""
api_response = None
if cached_item_api_response:
api_response = cached_item_api_response
elif item_id:
api_response = ... # make api call using item_id
else:
#ERROR
... #do stuff
或者,这是比较合适的?
class C:
"""Seems even more awkward to have different method calls"""
def a_method(item_id):
api_response = ... # make api call using item_id
api_response_logic(api_response)
def b_method(cached_api_response):
api_response_logic(cached_api_response)
def api_response_logic(api_response):
... # do stuff
感谢您的编辑,但通常我会建议使用代表而不是继承,因为它使类更灵活。 – Rickard
如果这不是你的意图,对不起改变它。这仅仅是一个Python问题,你的代码不是Python,所以我尽我所能猜测 - 随时回滚或更改它以反映你的意图。 (好的答案,已经得到了我的+1) – agf