0

这是一个丑陋的,高维护的工厂。我真的只需要一种方法来使用字符串来实例化一个名称与字符串匹配的对象。我认为元类是答案,但我不知道如何应用它:

from commands.shVersionCmd import shVersionCmd
from commands.shVRFCmd import shVRFCmd
def CommandFactory(commandnode):
    if commandnode.attrib['name'] == 'shVersionCmd': return shVersionCmd(commandnode)        
    if commandnode.attrib['name'] == 'shVRFCmd': return shVRFCmd(commandnode)
4

4 回答 4

2

您可以使用该函数查找全局名称,该globals()函数返回一个字典:

from commands.shVersionCmd import shVersionCmd
from commands.shVRFCmd import shVRFCmd

# An explicit list of allowed commands to prevent malicious activity.
commands = ['shVersionCmd', 'shVRFCmd']

def CommandFactory(commandnode):
    cmd = commandnode.attrib['name']
    if cmd in commands:
        fn = globals()[cmd]
        fn(commandnode)
于 2013-02-23T13:46:40.933 回答
0

eval是你的朋友:

from commands import *
def CommandFactory(commandnode):
    name=commandnode.attrib['name']
    assert name in ( "shVersionCmd", "shVRFCmd" ), "illegal command"
    return eval(name+"."+name)(commandnode)

请注意,如果您确定name永远不会包含任何非法命令,您可以删除assert并将该功能变成无维护的乐趣。如有疑问,请将其保留在一个地方并将列表保留在一个地方。

于 2013-02-23T13:14:22.490 回答
0

这个答案如何在 Python 中创建匿名函数而不用洗礼?讨论如何基于键干净地调用代码块

于 2013-02-23T13:27:16.933 回答
0

我个人的偏好是改变工厂和命令实现之间的依赖关系,以便每个命令都向工厂注册自己。

示例实现:

文件命令/__init__.py:

import pkgutil
import commands

_commands = {}

def command(commandCls):
    _commands[commandCls.__name__] = commandCls
    return commandCls

def CommandFactory(commandnode):
    name = commandnode.attrib['name']
    if name in _commands.keys():
        return _commands[name](commandnode)

# Load all commands
for loader, module_name, is_pkg in  pkgutil.walk_packages(commands.__path__):
    if module_name!=__name__:
        module = loader.find_module(module_name).load_module(module_name)

文件命令/mycommand.py:

from commands import command

@command
class MyCommand(object):    
    def __init__(self, commandnode):
        pass

小测试:

from commands import CommandFactory

# Stub node implementation
class Node(object):
    def __init__(self, name):
        self.attrib = { "name": name }

if __name__=='__main__':
    cmd = CommandFactory(Node("MyCommand"))
    assert cmd.__class__.__name__=="MyCommand", "New command is instance of MyCommand"
    cmd = CommandFactory(Node("UnknownCommand"))
    assert cmd is None, "Returns None for unknown command type"
于 2013-02-23T14:33:34.607 回答