如何读取(python[,argspecs])?

如何读取(python[,argspecs])?,python,Python,我尝试创建这样的模拟对象,但不想手动指定基(因为我不需要任何基): 这里我们有类似样式的argspec,complex允许默认为real、imag或两者(argspec的行为类似于complex(real=0,imag=0): 一些内置函数,例如slice,range,当然还有许多其他函数,都不允许您命名参数: >>> slice(stop=2) # I expected to get a slice(None, 2) Traceback (most recent call

我尝试创建这样的模拟对象,但不想手动指定基(因为我不需要任何基):

这里我们有类似样式的argspec,complex允许默认为real、imag或两者(argspec的行为类似于
complex(real=0,imag=0)

一些内置函数,例如
slice
range
,当然还有许多其他函数,都不允许您命名参数:

>>> slice(stop=2)  # I expected to get a slice(None, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: slice() does not take keyword arguments
然后,
datetime
有一个类似的argspec(带方括号的奇怪的argspec),但不介意使用kwargs:

>>> print(datetime.__doc__)
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
The year, month and day arguments are required. tzinfo may be None, or an
instance of a tzinfo subclass. The remaining arguments may be ints.
>>> datetime(year=2014, month=7, day=17)
datetime.datetime(2014, 7, 17, 0, 0)

问:python是否允许您使用默认值来避免这些意外情况,这是否有一些押韵或原因/一致性?或者这真的只是尝试和错误,并且熟悉该语言吗?

如果文档没有明确地将某个参数描述为命名参数,那么您不应该这样做假设它有一个名称。即使事实上确实有名称(例如Python代码中定义的大多数函数),这也是正确的,因为除非文档将其描述为命名参数,否则不会做出任何承诺。实现可以自由更改名称或要求将其作为位置参数传递

也就是说,在许多情况下,文档是有缺陷的,并且不会在参数打算或甚至要求将其作为命名参数传递时将其描述为命名参数。这些情况确实需要熟悉该语言,以便阅读字里行间的内容并弄清楚您应该做什么


顺便说一句,通过传递
()
作为基础。
类型
将使
对象
成为基础,因为所有新样式类都是从
对象
派生的。你不能用这种方式创建一个无基础的旧样式类。

这听起来像是C中实现的函数不带关键字参数的问题。另请参阅链接。天啊,真是一团糟:(我见过有人显式地传递
(object,)
作为前面的基础,你是说这在python2中是多余的吗?顺便说一句,我的示例代码在python3中,当时没有旧式类……我不会说多余,而是显式的。
type
的文档实际上没有说明传递空元组时会发生什么。
>>> complex(imag=7)
7j
>>> slice(stop=2)  # I expected to get a slice(None, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: slice() does not take keyword arguments
>>> type('', (), {})
<class '__main__.'>
>>> type('', bases=(), dict={})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type.__init__() takes no keyword arguments
>>> print(datetime.__doc__)
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
The year, month and day arguments are required. tzinfo may be None, or an
instance of a tzinfo subclass. The remaining arguments may be ints.
>>> datetime(year=2014, month=7, day=17)
datetime.datetime(2014, 7, 17, 0, 0)