Tuesday, February 1, 2011

Re: DRY and static attribute for multiple classes.

On 1 Feb 2011, at 21:05, Marc Aymerich wrote:

> Hi all,
> I want to provide an encapsulated static attribute called _registry
> for several classes.
>
> I try to use inheritance in order to make it DRY: all classes inherit
> from a BaseClass that implements the _registry encapsulation. But with
> inheritance it doesn't work how I want, because a single instance of
> the _registry is shared between all of the inherited classes, and I
> want to have an independent _registry for every class.
>
> How can I do that without coping all the code in every class?


Create your base class with the _registry attribute like so,

class MyBaseClass(models.Model)
_registry = models.IntegerField()
class Meta:
abstract = True

With 'abstract = True'; when you inherit from MyBaseClass the child classes will have their own _registry columns in the DB (rather than sharing a common table).

Cheers,

aid


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