whats a clean开发者_Go百科 way to use different templates depending on an object class? other than buncha if statements
You can make a dict
, call it type2templ
, with types (i.e., classes) as the keys, and mako.template.Template
instances as the values -- then
t = type2templ.get(type(theobj), default_templ)
... t.render() ...
This assumes that theobj
is an instance of a new-style class (not the obsolete, best-avoided "legacy" classes that are still the default in Python 2 -- if you use those, you should definitely upgrade your code to new-style classes, but using theobj.__class__
is a workable, if hackish, replacement for type(theobj)
here). default_templ
is a default template instance to use for "none of the above" (if you'd rather have an exception when theobj
is of a non-recognized type, use square-bracket indexing instead of the .get
call).
Note that this doesn't (directly) "support inheritance" -- if (for example) class foo
maps in type2templ
to template bar
, then you make a subclass baz
of foo
but don't explicitly record in type2templ
what template its instances should use, you'll get the default template for baz
's instances. Supporting inheritance is more complex -- unless you just make the mako template instance one of the class attributes, of course, which makes it trivial (just theobj.thetempl
if you name that attribute thetempl
!-), but I do understand to separate the view from the model.
精彩评论