2013-02-18 44 views
1

我想實現一個基於插件的文件上傳器,它可以上傳文件到不同的服務。它從一個目錄加載所有的python模塊,然後根據要上傳的服務調用它們。自定義ABC類:__new()__需要正好4個參數(1給出)

我有一個簡單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

您註冊元類,而不是插件本身;

>>> 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對象是類,而不是實例。

+0

嘗試了您的建議。從對象繼承後得到相同的錯誤 – Gokul 2013-02-18 10:34:10

+0

@Gokul:更新了答案;你正在註冊錯誤的對象。 – 2013-02-18 10:43:31

+0

這很好。謝謝,但如果加載的插件文件有多個類會發生什麼。我們如何創建特定類的對象 – Gokul 2013-02-18 10:49:28

相關問題