2013-04-04 18 views
2

我想創建一個NumPy數組充滿了對象,我想知道是否有一種方式,我可以廣播到整個數組爲每個對象做一些事情。在np.array廣播函數調用

代碼:

class player: 
    def __init__(self,num = 5): 
     self.num = num 

    def printnum(): 
     print(self.num) 
... 

objs = np.array([player(5),player(6)],dtype=Object) 
objs.printnum() 

因爲它代表這個返回一個錯誤。我已經嘗試將dtype更改爲:_object按照手冊,但似乎沒有任何工作。

回答

0

一個numpy的對象數組不會繼承該對象的方法。 ndarray方法一般行爲對整個陣列

這並不適用於內置的工種或者,例如在:

In [122]: import numpy as np 

In [123]: n = 4.0 

In [124]: a = np.arange(n) 

In [125]: n.is_integer() 
Out[125]: True 

In [126]: a.is_integer() 
--------------------------------------------------------------------------- 
AttributeError: 'numpy.ndarray' object has no attribute 'is_integer' 

NumPy的廣播與逐元素的運營商完成的,例如除了:

In [127]: n 
Out[127]: 4.0 

In [128]: a 
Out[128]: array([ 0., 1., 2., 3.]) 

In [129]: n + a 
Out[129]: array([ 4., 5., 6., 7.]) 

如果您希望基本上對數組中的所有元素調用print,則可以簡單地重新定義方法,該方法由print調用。我會告誡你,你會因重寫該方法而失去信息。

In [148]: class player: 
    .....:  def __init__(self, num=5): 
    .....:   self.num = num 
    .....:  def __repr__(self): 
    .....:   return str(self.num) 
    .....:  

In [149]: objs = np.array([player(5), player(6)]) 

In [150]: objs 
Out[150]: array([5, 6], dtype=object) 

In [151]: print objs 
[5 6] 

即使它看起來,這是不一樣的np.array([5,6])雖然:

In [152]: objs * 3 
---------------------- 
TypeError: unsupported operand type(s) for *: 'instance' and 'int' 

而且那裏你可以看到覆蓋__repr__的缺點。

更簡單的方式做到這一點是使用當前printnum()方法,但把它在一個循環:

In [164]: class player: 
    .....:  def __init__(self, num=5): 
    .....:   self.num = num 
    .....:  def printnum(self): 
    .....:   print(self.num) 
    .....:   

In [165]: for p in objs: 
    .....:  p.printnum() 
    .....: 
5 
6 

或者,也許定義你的方法返回一個字符串,而不是打印一個,然後進行列表理解:

In [169]: class player: 
    .....:  def __init__(self, num=5): 
    .....:   self.num = num 
    .....:  def printnum(self): 
    .....:   return str(self.num) 
    .....: 

In [170]: objs = np.array([player(5), player(6)]) 

In [171]: [p.printnum() for p in objs] 
Out[171]: ['5', '6'] 
+0

我明白了。我盡力避免使用for循環。謝謝,這回答了我的問題。 – user2243024 2013-04-04 16:25:42

+0

FYI,@ user2243024在數組上廣播的'element-wise'函數的類型(我使用'+'作爲示例)稱爲['ufunc's](http://docs.scipy.org/doc/) numpy的/參照/ ufuncs.html) – askewchan 2013-04-04 18:50:26

0

在你的代碼夫婦錯別字:printnum()需要self Arg和Object - >object

class player: 
    def __init__(self, num=5): 
     self.num = num 

    def printnum(self): 
     print(self.num) 


objs = np.array([player(5),player(6)], dtype=object) 

# It's not a "broadcast" (what you mean is map), but it has the same result 
# plus it's pythonic (explicit + readable) 
for o in objs: 
    o.printnum() 

它看起來像你真正想要做的就是創建一個生成器對象。谷歌python generator yield,你會得到一些例子this