自定义ABC类:__ new()__正好需要4个参数(给定1个)

时间:2013-02-18 10:25:57

标签: python python-2.7

我想实现一个基于插件的文件上传器,它可以将文件上传到不同的服务。它从一个目录加载所有python模块,然后根据要上传的服务调用它们。

我有一个简单的BaseHandler,它只是所有插件的抽象基类

import abc

class BaseHandler():
   __metaclass__ = abc.ABCMeta

   @abc.abstractmethod
   def start(self,startString):
      return

我有一个简单的插件,它继承自BaseHandler

from BaseHandler import BaseHandler

class Cloud(BaseHandler):
    def start(self,startString): 
        return

加载插件并调用它们的实际代码

import logging
import os
import sys
from BaseHandler import BaseHandler

all_plugins = {}

def load_plugins():
    plugin_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),"Handlers")
    plugin_files = [x[:-3] for x in os.listdir(plugin_dir) if x.endswith(".py")]
    sys.path.insert(0,plugin_dir)
    for plugin in plugin_files:
        mod = __import__(plugin)
    logging.info('Plugins have been loaded from the directory '+plugin_dir)
    for plugin in BaseHandler.__subclasses__():
        logging.info('Plugin:'+plugin.__name__)    
    return BaseHandler.__subclasses__()

logging.basicConfig(level=logging.DEBUG)
loadedPlugins = load_plugins()

for plugin in loadedPlugins:
    all_plugins[plugin.__name__]= plugin.__class__
    handle = all_plugins[plugin.__name__]()

当我尝试在脚本的最后一行创建插件的实际对象时

    handle = all_plugins[plugin.__name__]()

我收到错误TypeError: __new__() takes exactly 4 arguments (1 given)

编辑:添加完整追溯

Traceback (most recent call last):
   File "C:\TestCopy\Test.py", line 24, in <
module>
    handle = all_plugins[plugin.__name__]()
TypeError: __new__() takes exactly 4 arguments (1 given)

1 个答案:

答案 0 :(得分:1)

您正在注册元类,而不是插件本身;

>>> BaseHandler()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class BaseHandler with abstract methods start

我认为你的意思是存储插件本身:

all_plugins[plugin.__name__] = plugin

__class__属性是BaseHandler类; plugin个对象是类,而不是实例。