目前Python函数定义中是不能有/的,你应该看的是help或者是signature。
/的含义是之前的参数都是positional-only:
>>> help(binascii.b2a_base64)
b2a_base64(data, /, *, newline=True)
Base64-code line of data.
>>> import binascii
>>> binascii.b2a_base64(b'foo')
b'Zm9v\n'
>>> binascii.b2a_base64(data=b'foo')
Traceback (most recent call last):
File "", line 1, in
TypeError: b2a_base64() takes exactly 1 positional arguments (0 given)
上面的示例在3.6中可能不work,需使用其他版本。
/到*之间的参数可以被用作positional argument和keyword argument:
>>> help(int.to_bytes)
to_bytes(self, /, length, byteorder, *, signed=False)
Return an array of bytes representing an integer.
length
Length of bytes object to use. An OverflowError is raised if the
integer is not representable with the given number of bytes.
byteorder
The byte order used to represent the integer. If byteorder is 'big',
the most significant byte is at the beginning of the byte array. If
byteorder is 'little', the most significant byte is at the end of the
byte array. To request the native byte order of the host system, use
`sys.byteorder' as the byte order value.
signed
Determines whether two's complement is used to represent the integer.
If signed is False and a negative integer is given, an OverflowError
is raised.
>>> (777).to_bytes(4, 'little')
b'\t\x03\x00\x00'
>>> (777).to_bytes(length=4, byteorder='little')
b'\t\x03\x00\x00'
*之后的参数是keyword-only:
>>> binascii.b2a_base64(b'foo', False)
Traceback (most recent call last):
File "", line 1, in
TypeError: b2a_base64() takes at most 1 positional arguments (2 given)
>>> binascii.b2a_base64(b'foo', newline=False)
b'Zm9v'
目前用pure Python是不支持positional-only argument的(除了*args),所以你一般只能看到C写的函数signature里有/,比如内置函数:
>>> help(bytes.split)
split(self, /, sep=None, maxsplit=-1)
Return a list of the sections in the bytes, using sep as the delimiter.
sep
The delimiter according which to split the bytes.
None (the default value) means split on ASCII whitespace characters
(space, tab, return, newline, formfeed, vertical tab).
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
但是你也可以用inspect生成一下带/的signature,比如:
>>> from inspect import *
>>> sig = inspect.signature(foo)
>>> sig
>>> params = sig.parameters.copy()
>>> params['a'] = params['a'].replace(kind=Parameter.POSITIONAL_ONLY)
>>> params['b'] = params['b'].replace(kind=Parameter.POSITIONAL_ONLY)
>>> foo.__signature__ = inspect.Signature(params.values())
>>> signature(foo)
关于positional-only argument有一个draft PEP:PEP 457 -- Syntax For Positional-Only Parameterswww.python.org