Python - 最好有多个方法或许多可选参数?

10 python api caching coding-style optional-parameters

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

我不完全确定使用可选参数或使用多个方法是否更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
Run Code Online (Sandbox Code Playgroud)

或这个:

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
Run Code Online (Sandbox Code Playgroud)

或者这更合适?

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
Run Code Online (Sandbox Code Playgroud)

Ric*_*ard 5

通常在编写方法时,可以认为方法/对象应该做一件事而且应该做得好.如果你的方法得到越来越多的参数,这些参数需要你的代码中有越来越多的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)
Run Code Online (Sandbox Code Playgroud)

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