gpt4 book ai didi

Python - 最好有多种方法或大量可选参数?

转载 作者:太空狗 更新时间:2023-10-29 18:30:55 25 4
gpt4 key购买 nike

我有一个向远程 API 发出请求的类。我希望能够减少我调用的电话数量。我的类中的一些方法进行相同的 API 调用(但出于不同的原因),所以我希望它们能够“共享”缓存的 API 响应。

我不完全确定是使用可选参数还是使用多个方法更符合 Python 风格,因为如果方法进行 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

最佳答案

通常在编写方法时,人们可能会争辩说方法/对象应该做一件事,而且应该做得很好。如果您的方法获得越来越多的参数,而这些参数在您的代码中需要越来越多的 ifs,那可能意味着您的代码正在做不止一件事。特别是如果这些参数触发完全不同的行为。相反,也许可以通过使用不同的类并让它们重载方法来产生相同的行为。

也许你可以使用类似的东西:

class BaseClass(object):
def a_method(self, item_id):
response = lookup_response(item_id)
return response

class CachingClass(BaseClass):
def a_method(self, item_id):
if item_id in cache:
return item_from_cache
return super(CachingClass, self).a_method(item_id)

def uncached_method(self, item_id)
return super(CachingClass, self).a_method(item_id)

这样您就可以拆分如何查找响应和缓存的逻辑,同时还可以让 API 的用户灵活地决定他们是否需要缓存功能。

关于Python - 最好有多种方法或大量可选参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7150987/

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