What are some (concrete) use-cases for metaclasses?

前端 未结 19 1051
悲&欢浪女
悲&欢浪女 2020-12-07 06:51

I have a friend who likes to use metaclasses, and regularly offers them as a solution.

I am of the mind that you almost never need to use metaclasses. Why? because I

19条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 07:28

    the answer from @Dan Gittik is cool

    the examples at the end could clarify many things,I changed it to python 3 and give some explanation:

    class MetaMetaclass(type):
        def __new__(meta, name, bases, attrs):
            def __new__(meta, name, bases, attrs):
                cls = type.__new__(meta, name, bases, attrs)
                cls._label = 'Made in %s' % meta.__name__
                return cls
    
            attrs['__new__'] = __new__
            return type.__new__(meta, name, bases, attrs)
    
    #China is metaclass and it's __new__ method would be changed by MetaMetaclass(metaclass)
    class China(MetaMetaclass, metaclass=MetaMetaclass):
        __metaclass__ = MetaMetaclass
    
    #Taiwan is metaclass and it's __new__ method would be changed by MetaMetaclass(metaclass)
    class Taiwan(MetaMetaclass, metaclass=MetaMetaclass):
        __metaclass__ = MetaMetaclass
    
    #A is a normal class and it's __new__ method would be changed by China(metaclass)
    class A(metaclass=China):
        __metaclass__ = China
    
    #B is a normal class and it's __new__ method would be changed by Taiwan(metaclass)
    class B(metaclass=Taiwan):
        __metaclass__ = Taiwan
    
    
    print(A._label)  # Made in China
    print(B._label)  # Made in Taiwan
    
    
    • everything is object,so class is object
    • class object is created by metaclass
    • all class inheritted from type is metaclass
    • metaclass could control class creating
    • metaclass could control metaclass creating too(so it could loop for ever)
    • this's metaprograming...you could control the type system at running time
    • again,everything is object,this's a uniform system,type create type,and type create instance

提交回复
热议问题