繁体   English   中英

Python'AttributeError:'function'对象没有属性'min''

[英]Python 'AttributeError: 'function' object has no attribute 'min''

首先,对这两个问题的明显程度表示歉意; 我对此非常陌生,不知道我在做什么。

我正在尝试编写一些东西来将 Scipy 函数用于样条插值到值数组。 我的代码目前看起来像这样:

import numpy as np
import scipy as sp
from scipy.interpolate import interp1d

x=var
x1 = ([0.1,0.3,0.4])
y1 = [0.2,0.5,0.6]

new_length = 25
new_x = np.linspace(x.min(), x.max(), new_length)
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)

但是当它到达线路时

new_x = np.linspace(x.min(), x.max(), new_length)

我收到以下错误:

AttributeError: 'function' object has no attribute 'min'

到目前为止,谷歌搜索等没有发现我理解的任何内容。 这是什么意思,我该如何解决?

第二个问题:如何一次输入多行代码? 目前,如果我尝试复制整个内容然后将其粘贴到 PyLab 中,它只会输入我代码的第一行,因此我必须一次将整个内容粘贴到一行中。 我该如何解决这个问题?

如果这条线

new_x = np.linspace(x.min(), x.max(), new_length)

正在生成错误消息

AttributeError: 'function' object has no attribute 'min'

那么x是一个函数,并且函数(通常)没有min属性,所以你不能调用some_function.min() x是什么? 在您的代码中,您仅将其定义为

x=var

我不确定var是什么。 var不是 Python 中的默认内置函数,但如果它是一个函数,那么要么您出于某种原因自己定义它,要么从某个地方获取它(假设您正在使用 Sage,或者您做了星型导入)像from sympy import * 。)

[更新:既然你说你在“使用 PyLab”,可能varnumpy.var ,它在 IPython 启动时被导入到作用域中。 我认为你的意思是“在--pylab模式下使用 IPython。]

您还定义了x1y1 ,但是后来的代码引用了xy ,所以感觉这段代码介于两个功能状态之间。

现在numpy数组确实有一个.min().max()方法,所以这个:

>>> x = np.array([0.1, 0.3, 0.4, 0.7])
>>> y = np.array([0.2, 0.5, 0.6, 0.9])
>>> new_length = 25
>>> new_x = np.linspace(x.min(), x.max(), new_length)
>>> new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)

会工作。 你的测试数据不会,因为插值需要至少 4 个点,你会得到

ValueError: x and y arrays must have at least 4 entries

第二个问题:如何一次输入多行代码? 目前,如果我尝试复制整个内容然后将其粘贴到 PyLab 中,它只会输入我代码的第一行,因此我必须一次将整个内容粘贴到一行中。 我该如何解决这个问题?

假设你在ipython被称为ipython --pylab或类似的东西,那么你可以简单地使用paste magic command 如果您尚未将paste定义为另一个变量,则将其称为%paste或简单地paste

In [8]: paste
import numpy as np
import scipy as sp
from scipy.interpolate import interp1d

x=var
x1 = ([0.1,0.3,0.4])
y1 = [0.2,0.5,0.6]

new_length = 25
new_x = np.linspace(x.min(), x.max(), new_length)
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)

## -- End pasted text --
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-b4e41f59d719> in <module>()
      3 from scipy.interpolate import interp1d
      4 
----> 5 x=var
      6 x1 = ([0.1,0.3,0.4])
      7 y1 = [0.2,0.5,0.6]

NameError: name 'var' is not defined

In [9]: 

将该行更改为:

new_x = np.linspace(min(x), max(x), new_length)

minmax不是列表的属性,它们是它们自己的函数。

当我调用timezone.now而不是timezone.now() timezone.now ,我遇到了类似的错误。 然后我尝试格式化我期望的DateTime值。 但它不是DateTime 这是一个函数。 这导致了关于“Month”不是“function”的属性的错误消息。

解决方法是在now之后简单地添加括号。 这会调用now函数并返回其结果,而不是返回now function对象本身。

愚蠢的错误,我知道。 但不容易排除故障。

我得到了类似的问题。

我的错误是我将变量和函数名称命名为相同。

我纠正了这一点,错误消失了。

Int 没有 min() 函数,但 min() 是一个内置函数。 您需要使用 min(x)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM