Shouldn't __metaclass__ force the use of a metaclass in Python?

前端 未结 3 409
日久生厌
日久生厌 2021-01-18 13:23

I\'ve been trying to learn about metaclasses in Python. I get the main idea, but I can\'t seem to activate the mechanism. As I understand it, you can specify M to be as the

3条回答
  •  青春惊慌失措
    2021-01-18 13:48

    The syntax of metaclasses has changed in Python 3.0. The __metaclass__ attribute is no longer special at either the class nor the module level. To do what you're trying to do, you need to specify metaclass as a keyword argument to the class statement:

    p = print
    
    class M(type):
        def __init__(*args):
            type.__init__(*args)
            print("The rain in Spain")
    
    p(1)
    class ClassMeta(metaclass=M): pass
    

    Yields:

    1
    The rain in Spain
    

    As you'd expect.

提交回复
热议问题