DRY and static attribute for multiple classes.

Marc Aymerich glicerinu at gmail.com
Wed Feb 2 06:53:57 EST 2011


On Feb 2, 12:11 am, Peter Otten <__pete... at web.de> wrote:
> 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?
>
> If you want to go fancy use a metaclass:
>
> >>> class Base(object):
>
> ...     class __metaclass__(type):
> ...             def __init__(self, *args):
> ...                     type.__init__(self, *args)
> ...                     self.per_class = []
> ...>>> class A(Base): pass
> ...
> >>> A().per_class is A().per_class
> True
> >>> class B(Base): pass
> ...
> >>> B().per_class is B().per_class
> True
> >>> A().per_class is B().per_class
>
> False


Hi!,
Unfortunately per_class attribute losses the "independence" when I try
to mix it with django models.Model .

from django.db import models
class Plugin(models.base.ModelBase):
    class __metaclass__(type):
        def __init__(self, *args):
            type.__init__(self, *args)
            self.per_class = []

class BaseService(models.Model):
    class Meta:
        abstract = True

    __metaclass__ = Plugin

class VirtualHost(BaseService):
    name = models.CharField(max_length=10)

class SystemUser(BaseService):
    name = models.CharField(max_length=10)


>>> VirtualHost.per_class is SystemUser.per_class
True

What am I doing wrong?

Thanks again!



More information about the Python-list mailing list