在 python 钩子 __prepare__ 中使用 **kwargs

Use of **kwargs in python hook __prepare__

我无法从 python 文档中理解如何使用 hook __prepare__ 的 kwargs。

Once the class namespace has been populated by executing the class body, the class object is created by calling metaclass(name, bases, namespace, **kwds) (the additional keywords passed here are the same as those passed to prepare).

这是否意味着在填充 class 命名空间后,我们可以使用这些关键字参数来添加可用于 class 的额外属性?如果是,那么我们如何以及在何处将值传递给它,以便根据某些条件用不同的属性填充它,因为,afaik 在填充 class 命名空间之后对 __prepare__ 的调用应该是隐式的.

您可以通过 class 语句将关键字参数传递给元类构造函数。它并没有多大用处,除了用你熟悉的 Python 的晦涩功能给人们留下深刻印象。

关键字将传递给 __prepare____new____init__,但如果您只覆盖 __new__,则 __init__ 和 [=12 都不会=] 会抱怨意外的额外参数。

class Meta(type):
    def __new__(cls, name, bases, namespace, **kwargs):
        print("Got keywords in __new__: {}".format(kwargs))
        return super().__new__(cls, name, bases, namespace)

    def __prepare__(name, bases, **kwargs):
        print("Got keywords in __prepare__: {}".format(kwargs))
        return {}

class Klass(metaclass=Meta, key1=1, key2="fred"):                   # keywords used here!!!!
    pass

您不需要使用 **kwargs 语法来捕获参数。如果愿意,您可以明确命名它们(尽管它们只能作为关键字传递,而不能作为位置参数传递)。