In Django, I'd like to implement __getitem__
on a class level (so in the below example, I want to do Alpha['a']
). I've found that I need a metaclass for this: just like it this needs to be implemented on a class to make it accessible on the instance, it must be implemented on a metaclass to use it on class level, as I understand it.
class AlphaMeta(type):
a = 7
def __getitem__(self, key):
return getattr(self, key)
class Alpha(models.Model):
value = models.CharField(max_length = 64, default = '')
__metaclass__ = AlphaMeta
print Alpha['a']
The problem is that I get the error below. It works fine if Alpha is a normal new-style class (class Alpha(object)
), but for a more complex base it needs more. However, I don't unstand what it wants from me, as I don't understand what the metaclasses of all it's bases
are.
metaclass conflict: the metaclass of a derived class must be a
(non-strict) subclass of the metaclasses of all it's bases
I'm very new to metaclasses; any hints are greatly appreciated!
EDIT: model fields go in Alpha
rather than AlphaMeta