python - Python 3 中的类 "keyword arguments"

标签 python class python-3.x

我从 __build_class__ 的文档字符串中注意到了这一点:

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

Internal helper function used by the class statement.

让我感兴趣的部分是 **kwds 部分。类定义可以采用关键字参数吗?我试过了,但是我得到了一个非常奇怪的错误:

>>> class Test(a=1):
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type() takes 1 or 3 arguments

这是怎么回事? Python 3 中的类能否以某种方式接受关键字参数?也许需要一个特殊的元类?

最佳答案

Can classes in Python 3 somehow accept keyword arguments?

是的。 class 语句中除 metaclass 之外的任何关键字参数都传递给元类。如果指定了 metaclass 参数,则它被用作元类;否则,元类是 type。参见 PEP 3115了解更多详情。

关于python - Python 3 中的类 "keyword arguments",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21360224/

相关文章:

java - Android 上增强基色类

c++ - 继承类问题

python - 如何从列表中删除/删除每个第 n 个元素?

python-3.x - 为什么 file.tell() 会影响编码?

Python:如何使数组的每个项重复,并将相同的项组合在一起

python - 如何比较两个 numpy 数组并通过调整将缺失值添加到另一个

python - 提高python代码的速度

python - 从 PyParsing 中的字符串中检索多个重叠匹配项

java - Java-不可能的错误?

python - 如何让游戏角色(用户) Action 流畅?