【发布时间】:2014-11-19 23:25:52
【问题描述】:
我是 python 和 OOP 概念的新手,我无法理解某些事情,比如为什么有些函数会改变原始对象而有些不会。为了更好地理解它,我在下面的代码 sn-p 中将我的困惑放在了 cmets 中。任何帮助表示赞赏。谢谢。
from numpy import *
a = array([[1,2,3],[4,5,6]],float)
print a
array([[ 1., 2., 3.],
[ 4., 5., 6.]]) ### Result reflected after using print a
a.reshape(3,2)
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.]]) ### Result reflected on IDE after applying the reshape function
print a
array([[ 1., 2., 3.],
[ 4., 5., 6.]]) ### It remains the same as original value of "a", which is expected.
a.fill(0)
print a
[[ 0. 0. 0.]
[ 0. 0. 0.]] ### It changed the value of array "a" , why?
#############
type(reshape) ### If i try to find the type of "reshape" , i get an answer as "function" .
<type 'function'>
type(fill) ### I get a traceback when i try to find type of "fill", why?
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
type(fill)
NameError: name 'fill' is not defined
我的问题是:
1) 我如何知道哪些函数(考虑到“填充”是一个函数)会改变我的原始对象值(在我的例子中是“a”)?
2)考虑(如果我错了,请纠正我)如果“fill”是一个函数,那么为什么它会改变对象“a”的原始值?
3) 为什么我在使用 type(fill) 时会得到回溯?
【问题讨论】:
-
给定函数可以改变或不改变对象输入对象的值。在 NumPy 中,许多函数都带有
out参数,它告诉函数将答案放在这个对象中...... -
@Saullo Castro ,感谢您的回复,如果是这样,那么对于像我这样的人(谁是新手)来说,学习我怎么知道哪个函数有“out”参数以及谁没有,反正有没有看到或者学完语言就直观了。顺便问一下什么是“out”参数?
-
check the np.multiply 函数例如...并查看
out参数 -
通常 ndarray 方法正在就地执行操作,而模块方法正在返回新数组,除非您传递
out参数...实际上似乎当您执行a.sort()时实际调用np.sort(a, out=a) -
因为
fill()是ndarray方法......正如我提到的“通常ndarray 方法正在就地执行操作”......我很好奇他们没有函数np.fill()
标签: python arrays function numpy methods