python - How do I create a simple metaclass? -
i've been doing python time now, , i've understood meaning of metaclasses, i've never needed one. think best solution problem metaclass (correct me if there's better way).
what i'm trying create system automatically adds class variable n
, list instances
each class of mine. here's simplified example of 1 class:
class foo: n = 0 instances = [] def __init__(self): self.index = foo.n foo.n += 1 foo.instances.append(self)
this structure should implemented 7 or 8 classes of mine, , thinking metaclass might me here. know can use foo.__metaclass__ = mymetaclass
attribute use metaclass, how create metaclass?
actually, using base class work out better here:
class instanceslist(object): def __new__(cls, *args, **kw): if not hasattr(cls, 'instances'): cls.instances = [] return super(instanceslist, cls).__new__(cls, *args, **kw) def __init__(self): self.index = len(type(self).instances) type(self).instances.append(self) class foo(instanceslist): def __init__(self, arg1, arg2): super(foo, self).__init__() # foo-specific initialization
Comments
Post a Comment