How do I create a simple metaclass?

有些话、适合烂在心里 提交于 2019-12-01 00:13:55

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

Please, do not be afraid to learn how to use metaclasses. Few people know the magic they can perform:

#!/usr/bin/env python3

def main():
    x = Foo()
    print('x.index:', x.index)
    print('x.n:', x.n)
    print('x.instances:', x.instances)
    print('x.instances[0] == x:', x.instances[0] == x)

class MyMetaClass(type):

    def __new__(cls, name, bases, namespace):
        namespace.setdefault('n', 0)
        namespace.setdefault('instances', [])
        namespace.setdefault('__new__', cls.__new)
        return super().__new__(cls, name, bases, namespace)

    @staticmethod
    def __new(cls, *args):
        instance = cls.__base__.__new__(cls)
        instance.index = cls.n
        cls.n += 1
        cls.instances.append(instance)
        return instance

class Foo(metaclass=MyMetaClass):

    def __init__(self):
        print('Foo instance created')

if __name__ == '__main__':
    main()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!