在调用type()
没有参数的builtin时,Python中存在这个错误:
TypeError: type() takes 1 or 3 arguments
Run Code Online (Sandbox Code Playgroud)
我们如何定义这样的方法?有内置的方式吗?或者我们需要做这样的事情:
>>> def one_or_three(*args):
... if len(args) not in [1,3]:
... raise TypeError("one_or_three() takes 1 or 3 arguments")
...
>>> one_or_three(1)
>>> one_or_three()
TypeError: one_or_three() takes 1 or 3 arguments
>>> one_or_three(1,2)
TypeError: one_or_three() takes 1 or 3 arguments
Run Code Online (Sandbox Code Playgroud)
首先,类型不是原生 Python(至少在 CPython 中),而是 C。
该inspect
模块可以轻松确认(即使记录为内置函数,type
在 CPython 中作为类实现):
>>> print(inspect.signature(type.__init__))
(self, /, *args, **kwargs)
>>> print(sig.parameters['self'].kind)
POSITIONAL_ONLY
Run Code Online (Sandbox Code Playgroud)
参数 kind 为POSITIONAL_ONLY
,Python 中无法创建该参数。
这意味着不可能准确地再现类型的行为。
Python 源代码仅允许对可变数量的参数使用 2 个签名:
3 个参数,其中 2 个是可选的:
type(object_or_name, bases = None, dict = None)
Run Code Online (Sandbox Code Playgroud)
这将是非常不同的,因为它会很高兴地接受type(obj, None)
,这绝对不是这里所期望的
一个简单的参数,其长度将被手工*args
测试- 您的建议。这将更接近本机行为,因为它确实需要 1 或 3 个参数,无论值是什么。type
TL/DR:你的问题的答案是我们确实需要这样的东西。