Python的内置函数__build_class__有什么作用?

36

在Python 3.1中,有一个新的内置函数我不知道在builtins模块中:

__build_class__(...)
    __build_class__(func, name, *bases, metaclass=None, **kwds) -> class

    Internal helper function used by the class statement.

这个函数是做什么的?为什么它必须在内置函数中,如果它是内部函数?与type(name, bases, dict)函数有什么区别?

1个回答

34

编译PEP 3115元类

Guido van Rossum说:

The PEP proposes that the class statement accepts keyword arguments, *args, and **kwds syntax as well as positional bases. This is a bit messy to compile and execute, but we already have this, of course, in the code for calling regular functions.

So I think it would be acceptable to this into a call to a new (hidden) built-in function, named __build_class__. Then that this class definition:

  class C(A, B, metaclass=M, other=42, *more_bases, *more_kwds):
    ...

would translate into this:

  C = __build_class__(<func>, 'C', A, B, metaclass=M, other=42,
*more_bases, *more_kwds)

where <func> is a function object for the class body.


5
“类体函数对象”是什么? - DeFazer
2
您可以在Guido van Rossum的链接帖子中的代码示例中找到此信息。__build_class__将调用类似于locals = {}; func(locals)的内容。也就是说,对于一个类class X: y = 1,等效的函数体<func>将是:def func(locals): locals.y = 1 - filip

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接