Python 在调用不带参数的内置 type()
时出现此错误:
TypeError: type() takes 1 or 3 arguments
我们如何定义这样的方法? 有内置的方法吗?或者我们需要做这样的事情:
>>> 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
最佳答案
首先,类型不是原生 Python(至少在 CPython 中),而是 C。
inspect
模块可以很容易地确认它(即使记录为内置函数,type
在 CPython 中作为类实现):
>>> print(inspect.signature(type.__init__))
(self, /, *args, **kwargs)
>>> print(sig.parameters['self'].kind)
POSITIONAL_ONLY
参数种类为POSITIONAL_ONLY
,不能在Python中创建。
这意味着将无法完全重现类型的行为。
Python 源代码只允许 2 个签名用于可变数量的参数:
3 个参数,其中 2 个是可选的:
type(object_or_name, bases = None, dict = None)
这会非常不同,因为它会很乐意接受
type(obj, None)
这绝对不是这里所期望的一个简单的
*args
参数,其长度将手动测试 - 您的建议。这将更接近原生type
行为,因为它确实需要 1 或 3 个参数,无论值是什么。
TL/DR:您问题的答案是我们确实需要类似的方式。
关于python - 有没有内置的方法来定义一个接受 1 个参数或 3 个参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53261804/