Python3中省略号(...)用法介绍

      1. 省略号(...)是一个Python对象,叫Ellipsis,它没有方法,是一个单例对象(singleton object):

# 1. ...是一个python对象,叫Ellipsis
print(type(...)) # output: <class 'ellipsis'>
print(...) # output: Ellipsis
print(Ellipsis) #  output: Ellipsis
print(bool(...)) # output: True

      2. 它可用作Python解释器中的默认辅助提示符(default secondary prompt):

        3. 它用于访问和切片(accessing and slicing)多维数组/NumPy索引,注:不能在一个切片中有多个省略号

# 3. slice: we can not have multiple ellipsis in a single slicing
array = np.random.rand(2, 4) # a 2-dimensional matrix of order 2*4(rows*cols)
print(array); print(array[...]); print(array[Ellipsis]) # they are all equivalent
print(array[..., 0]); print(array[:,0]); print(array[Ellipsis, 0]) # they are all equivalent
print(array[0, ...])

      4. 它可用在类型提示中(in type hinting):

# 4. type hints
# 当函数的参数类型允许为Any
def inject(get_next_item: Callable[..., str]) -> None:
    ...

def foo(x: ...) -> None:
    ...

# 当函数的返回类型为Any
class flow:
    def __understand__(self, name: str, value: ...) -> None:
        ...

      5. 它可用作函数内部的pass语句:

# 5. used as Pass Statement inside Functions
# foo1 and foo2 styles are same
def foo1():
    pass

def foo2():
    ...

      6. 它可用作默认参数值:

# 6. used as a default argument value
def foo3(x = ...):
    return x

def foo4(x = None):
    return x

print("foo3:", foo3) # output: foo3: <function foo3 at 0x7f4e7ffcf5e0>
print("foo4:", foo4) # output: foo4: <function foo4 at 0x7f4e7ffcf550>

      以上内容主要参考:https://www.geeksforgeeks.org

      GitHubhttps://github.com/fengbingchun/Python_Test

  • 7
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值