1

我需要为几种不同的案例类型(在 Python 中)编写处理程序。所有这些类型的接口都是相同的,但处理逻辑不同。

一种选择是定义一个公共类,该类接收特定的处理程序类型作为 __init__ 参数之一:

class Handler:
   def __init__ (self, handlerType):
       self._handlerType = handlerType
       self._handler = handlerType.handleStuff

   def handleStuff(self, *args, **kwargs):
       return self._handler(args, kwargs)


# case specific handlers

class Handler_Case1:
   def handleStuff(self, *args, **kwargs):
       print 'Handling Case 1'


class Handler_Case2:
   def handleStuff(self, *args, **kwargs):
       print 'Handling Case 2'



if __name__ == '__main__':
   handlers = []
   handlers.append(Handler(Handler_Case1))
   handlers.append(Handler(Handler_Case2))
   for h in handlers:
       h.handleStuff()

但是,这会导致 TypeError:

TypeError:必须使用 Handler_Case1 实例作为第一个参数调用未绑定的方法 handleStuff()(改为获取元组实例)

另一种选择是模仿抽象函数,如下所示 “问:你能在 Python 中用 0 行代码实现抽象类吗?”):

class Handler:
  def handleStuff(self, *args, **kwargs): abstract
  def commonFunction(self):
       print 'Common function'


 # case specific handlers

 class Handler_Case1(Handler):
  def handleStuff(self, *args, **kwargs):
      print 'Handling Case 1'


 class Handler_Case2(Handler):
  def handleStuff(self, *args, **kwargs):
      print 'Handling Case 2'



 if __name__ == '__main__':
  handlers = []
  h1 = (Handler_Case1())
  h2 = (Handler_Case2())
  handlers.append(h1)
  handlers.append(h2)
  for h in handlers:
      h.handleStuff()
      print

所以,实际上,我有两个问题:

  1. 这两种方法中哪一种更pythonic?和
  2. 如何实现第一个?
4

1 回答 1

4

I might be missing some subtle intricacy in your question, but given your first example, what precludes you from doing something like this:

class HandlerCase1(object):
    def handle_stuff(self, *args, **kwargs):
        print "Handling case 1"


class HandlerCase2(object):
    def handle_stuff(self, *args, **kwargs):
        print "Handling case 2"


if __name__ == "__main__":
    handlers = []
    handlers.append(HandlerCase1())
    handlers.append(HandlerCase2())
    for h in handlers:
        h.handle_stuff()

And if you want the classes to share some common (base) functionality, is there something keeping you from doing this:

class Handler(object):
    def common_function(self):
        print "Common function"


class HandlerCase1(Handler):
    def handle_stuff(self, *args, **kwargs):
        print "Handling case 1"


class HandlerCase2(Handler):
    def handle_stuff(self, *args, **kwargs):
        print "Handling case 2"


if __name__ == "__main__":
    handlers = []
    handlers.append(HandlerCase1())
    handlers.append(HandlerCase2())
    for h in handlers:
        h.handle_stuff()
        h.common_function()
于 2009-04-12T20:50:25.977 回答