Python传入要用作动态属性的参数列表

时间:2013-03-25 15:57:44

标签: python list parameter-passing args

我有这个特定于Flask中的Jinja2模板(但与其中任何一个都没有特别相关,只是我正在努力构建更通用的上下文):

class MultipleMacroFor(object):
    def __init__(self, macro):
        self.macro = macro

    def renderable(self, macro_var):
        return get_template_attribute(self.macro, macro_var)

class ResponseItemMacros(MultipleMacroFor):
    def __init__(self):
        super(ResponseItemMacros, self).__init__(macro="macros/response_items.html")

    @property
    def general_macro(self):
        return self.renderable('general_macro')

RI = ResponseItemMacros()

用例的示例:

 RI.general_macro # returns the renderable 'general_macro' from 'macros/response_items.html' that can be used with in a Jinja2 template

我想谈谈这个:

class MultipleMacroFor(object):
    def __init__(self, macro, which_macros):
          self.macro = macro
          self.which_macros = which_macros

     # take which_macros and have them each be returnable as in the function above but
     # respond to the more general case, not specifically requiring construction  
     # @property
     # def (passed in var which_macro)(self):
     #   return self.renderable(passed in var which_macro)

RI = MultipleMacroFor(macro="macros/response_items.html", macros=['general', 'etc', 'etal'])

然后用例:

RI.general_macro #as above but without having to construct the intermediate ResponseItemsMacros class

并将传入的列表作为属性调用,仅基于传入列表动态构造,而不是手动构造为第一个示例。第一个示例需要从两个类手动构造我想要使用的实例。第二个是希望仅使用1个类,可以使用要调用的属性实例化,这将通过可渲染函数生成相关的命名宏。

只有我不确切知道如何做这个atm。任何输入赞赏。

1 个答案:

答案 0 :(得分:0)

你不能拥有每个实例的属性(或者至少不能没有搞乱 get_attribute ,这是你真正应该避免的)。最简单的解决方案是使用 getattr

class MultipleMacroFor(object):
    def __init__(self, macro, names):
        self._macro = macro
        self._names = names

    def get_renderable(self, macro_var):
        return get_template_attribute(self.macro, macro_var)

    def __getattr__(self, name):
        if name in self._names:
            return self.get_renderable(name)
        raise AttributeError(
            "object %s has no attribute '%s'" % (
                type(self).__name__, name)
            )

更复杂的方法是动态构建子类,然后实例化它。

class MultipleMacroFor(object):
    def __init__(self, macro, names):
        self._macro = macro
        self._names = names


    def get_renderable(self, macro_var):
        return get_template_attribute(self.macro, macro_var)

def MultipleMacroForFactory(macro, names):
    attrs = dict()
    for name in names:
        attrs[name] = property(
            lambda self, name=name: self.get_renderable(name)
            )

    clsname = "MultipleMacroFor%s" % "".join(
        name.capitalize() for name in names
        )

    return type(clsname, (MultipleMacroFor,), attrs)(macro, names)