简体   繁体   中英

Python passing in a list of parameters to be used as dynamic properties

I have this which is specific to Jinja2 templating within Flask(but is not specifically related to either, is just the context I'm working in to construct something more general):

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()

An example for a use case:

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

Which I want to turn into this:

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'])

then use case:

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

and have the list passed in be called as a property, only dynamically contructed based on the passed in list and not manually constructed as the first example. The first example requires manually constructing from two classes the instance I want to use. The second is the wish use just 1 class that can be instanced with properties to be called, which would work through the renderable function to produce the relevant named macro.

Only I don't know exactly how to do this atm. Any input appreciated.

You can't have per-instance properties (or at least not without messing with get_attribute , which is something you really should avoid). The simplest solution is to use 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)
            )

A more involved way is to dynamically build a subclass then instanciate it.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM