Type casting a base class to a derived one?
cliff at develix.com
Wed Jan 24 20:49:20 CET 2007
On Wed, 2007-01-24 at 11:37 -0800, Cliff Wells wrote:
> class Person: # assume this is something from the ORM
> name = "Kenny"
> class PersonRow ( Person ):
> def flatten_person ( p ):
> return "<span>omg, you've killed %p</span>" % p.name
> def flatten_personrow ( p ):
> return "<tr><td>%s</td></tr>" % p.name
> register_flattener ( PersonRow, flatten_personrow )
> register_flattener ( Person, flatten_person )
> Now, assuming a list of Person records were passed in as 'persons', then
> in the template the template author could simply use:
> div [
> # show the first person
> persons [ 0 ],
> # show a table of all persons
> table [
> [ PersonRow ( p ) for p in persons ]
I should add that the reason I don't want to just say, call
flatten_personrecord() directly from the template (which would be a
reasonable solution in this example) is because I have a longer-term
goal that would require an object at that point.
What I expect I'll end up doing is using a factory function that returns
the desired object at that point, but it will require a bit more
explanation at the template level than I'd like:
[ render_as ( PersonRow, p ) for p in persons ]
or something similar.
More information about the Python-list