[Tutor] inheritance/classmethods/metaclasses
Eric Abrahamsen
eric at ericabrahamsen.net
Thu Jun 19 15:50:01 CEST 2008
I'm probably in over my head here, but I really want to know how this
works, and I hope someone will be willing to take a moment to explain
it...
I'm making a few classes for a very simple ORM, where the classes
reflect objects that I'm persisting via pickle. I'd like to add and
delete instances via add() and delete() classmethods, so that the
classes can keep track of the comings and goings of their instances.
My main question is, how can I abstract this classmethod behavior for
several classes, either into a metaclass, or a super class? I've done
some very scary reading, and some fruitless experimentation, and am
over my head. I know the answer is probably "do something else
entirely", but I'd really like to know how this is supposed to work.
What I'd like is a Model class, which provides an add() classmethod
like this:
class Model(object):
@classmethod
def add(cls, *args)
inst = cls(args)
cls.instances.append(inst)
Then, say, a File class:
class File():
# inherit from Model, or use Model as a metaclass?
instances = []
def __init__(self, *args)
self.filename = args[0]
self.keyword = args[1]
The desired behavior, of course, is this:
File.add('somefilename','keywordforthisfile')
and to be able to extend this behavior to other classes.
Any pointers would be much appreciated...
Eric
More information about the Tutor
mailing list