sorry!
On 4 Okt., 01:26, momo2k <tkew...@googlemail.com> wrote:
> Hello,
>
> this may be a python-general question, but it came across my way while
> working with django:
> Imagine you have a model:
>
> class A(Model)
> name = CharField()
> type = SmallIntegerField(choices=SOME_TYPES)
>
> def do_something(self):
> fancy_things
>
> I want do_something() do different things based on the actual type of
> the instance. I know that this is a typical use case of subclassing,
> but for some reasons (mostly avoiding generic m2m-relationships) I
> decided to keep everything in one table.
> My current implementation uses python-style switches to solve this
> problem::
>
> def do_something(self):
> try:
> {TYPE1: do_something1,
> TYPE2: do_something2}[self.type]()
> except KeyError:
> raise ValueError('type not known')
>
> This is very verbose and not DRY.
> I thought about solving this problem by changing the base class on the
> fly using __bases__. But this seems to be very dirty. In addition,
> this would have to be done every time self.type changes. I don't know
> which hook I could use for this.
> Second thought was using a read property self.impl which provides the
> particualar implementations for a type:
>
> class _Type1Impl(object):
> def do_something(self):
> ...
>
> @property
> def impl()
> type_switch_here ...
>
> def do_something(self):
> return self.impl.do_something()
>
> But this is also some verbose because of the "redirection" to
> self.impl and I can imagine python provides much better ways to
> achieve my goal.
>
> Any suggestions?
>
> Greets
> momo
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
No comments:
Post a Comment