Skip to main content
 首页 » 编程设计

python之在 Python 中更改了对象

2024年10月25日10zfyouxi

我是 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 

我的问题是:

1) 我如何知道哪个函数(考虑到“fill”是一个函数)将改变我的原始对象值(在我的例子中是“a”)?

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

3) 为什么我在使用 type(fill) 时得到回溯?

请您参考如下方法:

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

下面是一些带有out参数的NumPy函数:

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

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

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

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


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

print(a.flags) 
 
C_CONTIGUOUS : True 
F_CONTIGUOUS : False 
OWNDATA : True 
WRITEABLE : True 
ALIGNED : True 
UPDATEIFCOPY : False