一个有趣的numpy题目------不同包里面的重名函数

一样的代码,两次调用的输出截然不同

100 numpy exercises 中有个有趣的题目

26.What is the output of the following script? (★☆☆)

print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))

在这里插入图片描述
两行打印分别是9和10,是不是有些奇怪?

分析原因

首先来看第一行打印:
print(sum(range(5),-1))
这里调用的是python原生的sum接口。

第二行,因为导入了numpy包,再调用sum()就会被numpy中sum()覆盖,因此第三行中的sum(),调用的已不是python原生的sum()接口了,而是numpy.sum()。

可以使用help(sum)确认调用的是哪个包里面的sum函数。

Help on built-in function sum in module __builtin__:

sum(...)
    sum(sequence[, start]) -> value
    
    Return the sum of a sequence of numbers (NOT strings) plus the value
    of parameter 'start' (which defaults to 0).  When the sequence is
    empty, return start.

Help on function sum in module numpy.core.fromnumeric:

sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>)
    Sum of array elements over a given axis.
    
    Parameters
    ----------
    a : array_like
        Elements to sum.
    axis : None or int or tuple of ints, optional
        Axis or axes along which a sum is performed.  The default,
        axis=None, will sum all of the elements of the input array.  If
        axis is negative it counts from the last to the first axis.
    
        .. versionadded:: 1.7.0
    
        If axis is a tuple of ints, a sum is performed on all of the axes
        specified in the tuple instead of a single axis or all the axes as
        before.
    dtype : dtype, optional
        The type of the returned array and of the accumulator in which the
        elements are summed.  The dtype of `a` is used by default unless `a`
        has an integer dtype of less precision than the default platform
:

下面的博客详细分析了具体原因。
https://stoneboy100200.github.io/2018/08/09/numpy-sum/
https://blog.csdn.net/linzch3/article/details/60141743

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值