gpt4 book ai didi

python - 如何创建一个简单的元类?

转载 作者:行者123 更新时间:2023-11-28 17:47:31 24 4
gpt4 key购买 nike

我已经使用 Python 一段时间了,我总能稍微理解元类的含义,但我从来不需要元类。现在我认为我的问题的最佳解决方案是元类(如果有更好的方法,请纠正我)。

我要创建的是一个系统,它会自动为我的每个类添加一个类变量 n 和一个列表 instances。这是一个类的简化示例:

class Foo:
n = 0
instances = []

def __init__(self):
self.index = Foo.n
Foo.n += 1
Foo.instances.append(self)

这个结构应该为我的 7 或 8 个类实现,我在想元类可能会在这里帮助我。我知道我可以使用 Foo.__metaclass__ = MyMetaclass 属性来使用元类,但我如何创建元类?

最佳答案

实际上,在这里使用基类会更好:

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

关于python - 如何创建一个简单的元类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15836263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com