问题描述
我一直在做Python一段时间,我总是有点理解元类的意义,但我从来没有需要一个。
现在我认为我的问题的最佳解决方案是一个元类(如果有更好的方法,请更正我)。
I've been doing Python for some time now, and I've always somewhat understood the meaning of metaclasses, but I've never needed one.Now I think the best solution for my problem is a metaclass (correct me if there's a better way).
我想创建的是一个系统自动向每个类别添加类变量 n
和列表 instances
。这里有一个简单的例子:
What I'm trying to create is a system which automatically adds a class variable n
and a list instances
to each class of mine. Here's a simplified example of one class:
class Foo:
n = 0
instances = []
def __init__(self):
self.index = Foo.n
Foo.n += 1
Foo.instances.append(self)
这个结构应该实现我的7或8类,我想一个元类可能会帮助我。
我知道我可以使用 Foo .__ metaclass__ = MyMetaclass
属性来使用元类,但是如何 / strong>元类?
This structure should be implemented for 7 or 8 classes of mine, and I was thinking that a metaclass might help me here.I know I can use the Foo.__metaclass__ = MyMetaclass
attribute to use the metaclass, but how do I create the metaclass?
推荐答案
实际上,使用基类会更好:
Actually, using a base class would 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
这篇关于如何创建一个简单的元类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!