对象在Python中被更改

2024-05-08 23:04:46 发布

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

我是python和OOP概念的新手,我无法理解某些事情,比如为什么有些函数会更改原始对象,而有些则不会。为了更好地理解它,我在下面的代码片段中添加了注释。感谢任何帮助。谢谢。在

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

我的问题是:

我的函数是怎样改变的?在

2)考虑(如果我错了,请纠正我)如果“fill”是一个函数,那么为什么它会改变对象“a”的原始值?在

3)当我使用type(fill)时,为什么要进行回溯?在


Tags: ofthe对象函数astypeitfunction
2条回答
  1. 阅读文档或尝试:)

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

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

给定函数可以更改输入对象,也可以不更改。在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

相关问题 更多 >