如何保持kwarg的数据类型完整?

2024-06-02 08:34:40 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我正在处理的脚本,我希望将数组传递给函数是可选的。我尝试这样做的方式是通过将有问题的变量(residue)设为kwarg

问题是,当我以这种方式执行时,python将kwarg的de-dtype从numpy.ndarray更改为dict。最简单的解决方案是使用以下方法将变量转换回np.array

    residue = np.array(residue.values())

但我不认为这是一个非常优雅的解决方案。所以我想知道是否有人能给我展示一种“更漂亮”的方法来实现这一点,并向我解释python为什么这么做

所讨论的功能是:

    #Returns a function for a 2D Gaussian model 
    def Gaussian_model2D(data,x_box,y_box,amplitude,x_stddev,y_stddev,theta,**residue):
        if not residue:
            x_mean, y_mean = max_pixel(data) # Returns location of maximum pixel value   
        else:
            x_mean, y_mean = max_pixel(residue) # Returns location of maximum pixel value
        g_init = models.Gaussian2D(amplitude,x_mean,y_mean,x_stddev,y_stddev,theta) 
        return g_init
     # end of Gaussian_model2D

使用以下命令调用该函数:

    g2_init = Gaussian_model2D(cut_out,x_box,y_box,amp,x_stddev,y_stddev,theta,residue=residue1)

我正在使用的Python版本是2.7.15


Tags: of函数boxinit方式gaussian解决方案mean
1条回答
网友
1楼 · 发布于 2024-06-02 08:34:40

请参阅the accepted answer here如果通过**kwargs传递参数,那么为什么总是获取映射对象(又称dictthe language spec says

If the form “**identifier” is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a new empty mapping of the same type.

换句话说,您描述的行为正是语言所保证的

这种行为的原因之一是,所有函数、包装器和底层语言(例如C/J)的实现都会理解**kwargs是参数的一部分,应该扩展到它的键值组合。 如果您想将额外的参数保留为特定类型的对象,则不能使用**kwargs来这样做;通过一个显式参数传递它,例如extra_args,它没有特殊的含义

相关问题 更多 >