【问题标题】:Object is changed in Python在 Python 中更改了对象
【发布时间】: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


【解决方案1】:

给定的函数可以改变或不改变输入对象。在 NumPy 中,许多函数都带有一个 out 参数,它告诉函数将答案放在这个对象中。

这里有一些带有out参数的NumPy函数:

这些函数可能会以ndarray 方法的形式提供,没有out 参数,在这种情况下执行就地操作。也许最著名的是:

一些函数和方法不使用out参数,尽可能返回内存视图:

  • 函数np.reshape()和方法ndarray.reshape()

ndarray.fill() 是子例程的一个示例,专门用作一种方法,就地更改数组。


每当您获得一个 ndarray 对象或其子类时,都可以根据 flags 属性的 OWNDATA 条目检查它是否是内存视图:

print(a.flags)

C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False

【讨论】:

    【解决方案2】:
    1. 阅读文档或尝试 :)

    2. a.reshape() 是对象 a 的方法,与 a.fill() 相同。它可以用 a 做任何事情。这不适用于 reshape(不是 a.reshape)——这是您从 from numpy import * 中的 numpy nodule 导入的函数。

    3. fill 不在 numpy 模块中(你还没有导入它),它是 ndarray 对象的成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      相关资源
      最近更新 更多