欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺析PEP570新語法: 只接受位置參數(shù)

 更新時間:2019年10月15日 09:00:25   作者:小明  
本文通過一個例子給大家介紹了PEP570新語法: 只接受位置參數(shù)的一些知識,感興趣的朋友跟隨小編一起看看吧

最近 PEP 570被接受了,其實(shí)要加的這個Positional-Only Parameters原來在內(nèi)置的C函數(shù)上有很多都用到了:

In : __builtin__.eval
Out: <function eval(source, globals=None, locals=None, /)>
In : __builtin__.len
Out: <function len(obj, /)>
In : __builtin__.divmod
Out: <function divmod(x, y, /)>

看它們的簽名,最后都有一個/,/用途是 在/左面的這些參數(shù),只能是位置參數(shù)(不能是關(guān)鍵字參數(shù)):

In : divmod(3, 2)
Out: (1, 1)
In : divmod(x=3, y=2)
---------------------------------------------------------------------------
TypeError                 Traceback (most recent call last)
<ipython-input-28-6668f56246b2> in <module>
----> 1 divmod(x=3, y=2)
TypeError: divmod() takes no keyword arguments

如果使用關(guān)鍵字參數(shù)的方式,會報錯。當(dāng)然這個錯有點(diǎn)莫名其妙。為什么要搞Positional-Only呢?就是強(qiáng)制使用者用位置參數(shù)!

再看一個例子(bytes):

In [68]: bytes??
Init signature: bytes(self, /, *args, **kwargs)
Docstring:
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object
...
In : bytes('哈哈', 'utf-8')
Out: b'\xe5\x93\x88\xe5\x93\x88'
In : bytes('哈哈', encoding='utf-8')
Out: b'\xe5\x93\x88\xe5\x93\x88'

雖然bytes也有/,但是它只約束了左邊的參數(shù)(這里只有一個self),之后的encoding可以用位置參數(shù),也能用關(guān)鍵字參數(shù)。

通過PEP 570,我們寫的Python代碼也可以支持了。你可以這樣寫:

def name(p1, p2, /, p_or_kw, *, kw):
def name(p1, p2=None, /, p_or_kw=None, *, kw):
def name(p1, p2=None, /, *, kw):
def name(p1, p2=None, /):
def name(p1, p2, /, p_or_kw):
def name(p1, p2, /):

在 Python 3.8 時我們就能使用這個新語法啦?,F(xiàn)在可以通過 PEP里面的幾個簡單例子,感受一下它的用法,期待喲

好了,就給大家介紹到這里,希望對大家有所幫助!

相關(guān)文章

最新評論