## Numpy如何实现对象数组？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (30)

```class site:
def __init__(self,a,...):
self.a = a
.... other properties ...
def set_a(self, new_a):
self.a = new_a```

```lattice = np.empty( (3,3), dtype=object)
lattice[:,:] = site(3)```

`lattice[0,0].set_a(5)`

```for i in range(3):
for j in range(3):
lattice[i,j] = site(a)```

### 2 个回答

vectorize：class's`__init__`function：

```import numpy as np

class Site:
def __init__(self, a):
self.a = a
def set_a(self, new_a):
self.a = new_a

vSite = np.vectorize(Site)

init_arry = np.arange(9).reshape((3,3))

lattice = np.empty((3,3), dtype=object)
lattice[:,:] = vSite(init_arry)```

`lattice[:,:] = site(3)`

```array([[<__main__.Site object at 0x1029d5610>,
<__main__.Site object at 0x1029d5610>,
<__main__.Site object at 0x1029d5610>],
[<__main__.Site object at 0x1029d5610>,
<__main__.Site object at 0x1029d5610>,
<__main__.Site object at 0x1029d5610>],
[<__main__.Site object at 0x1029d5610>,
<__main__.Site object at 0x1029d5610>,
<__main__.Site object at 0x1029d5610>]], dtype=object)```

`lattice = [ [Site(i + j) for i in range(3)] for j in range(3) ]`

```lattice = np.array( [ [Site(i + j) for i in range(3)] for j in range(3) ],
dtype=object)```

```array([[<__main__.Site object at 0x1029d53d0>,
<__main__.Site object at 0x1029d50d0>,
<__main__.Site object at 0x1029d5390>],
[<__main__.Site object at 0x1029d5750>,
<__main__.Site object at 0x1029d57d0>,
<__main__.Site object at 0x1029d5990>],
[<__main__.Site object at 0x1029d59d0>,
<__main__.Site object at 0x1029d5a10>,
<__main__.Site object at 0x1029d5a50>]], dtype=object)```