2014-09-25 78 views
1

我是Python和OOP概念的新手,我無法理解某些東西,比如爲什麼某些函數會改變原始對象而有些則不會。爲了更好地理解它,我在下面的代碼片段中將注意力放在了混淆之處。任何幫助表示讚賞。謝謝。對象在Python中更改

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)我要如何知道哪些功能(S)(考慮「補」是一個功能)將改變我原來的對象值(在我情況下它的「a」)?如果「fill」是一個函數,那麼爲什麼它改變了對象「a」的原始值?

3)爲什麼我使用類型(填充)時得到回溯?

+1

給定函數可以改變或者不是對象輸入對象值。在NumPy中,許多函數都帶有'out'參數,它告訴函數將答案放在這個對象中... – 2014-09-25 09:53:23

+0

@Saullo Castro,謝謝你的回覆,如果是這樣的話,對於像我這樣的人來說,是新的),學習如何知道哪個函數有「out」參數,誰沒有,有沒有看到它,或者在學習語言後變得直觀。順便說一下,「out」參數是什麼? – PKumar 2014-09-25 10:02:42

+1

[檢查np.multiply](http://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html)函數,例如...並查看'out'參數 – 2014-09-25 10:07:28

回答

1

給定的函數可以改變或不改變輸入對象。在NumPy中,許多函數都帶有一個out參數,它告訴函數將答案放在此對象中。

下面是一些 NumPy的功能與out參數:

可能發生的是,這些功能可作爲一個ndarray方法而不out參數,在這種情況下,代替執行所述操作。也許最有名的是:

的一些功能和方法不使用out參數,返回一個內存視圖時參考:

  • 功能np.reshape()和方法ndarray.reshape()

The ndarray.fill()是作爲方法專門提供的子例程的一個示例,它在原地更改數組。


每當你得到一個ndarray對象或它的子類,可以檢查它是否是一個存儲視圖或不基於flags屬性的OWNDATA條目:

print(a.flags) 

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

哇!感謝Owndata和flags屬性。 – PKumar 2014-09-25 10:59:31

1
  1. 閱讀docs或嘗試:)

  2. a.reshape()是()對象的方法,對相同a.fill。它可以做任何事情。這不適用於重塑(不是a.reshape) - 這是您從從numpy結節導入的函數。

  3. 填充不在numpy模塊中(您尚未導入它),它是ndarray對象的成員。