how to call the function of object in np.array
时间: 2024-02-19 15:57:54 浏览: 127
To call a function of an object in a NumPy array, you can use the `np.vectorize` function. This function applies a function to each element of a NumPy array, including elements that are objects.
Here is an example:
```python
import numpy as np
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
print(f"Hello, my name is {self.name}")
people = np.array([Person('John'), Person('Jane'), Person('Bob')])
# Define a function to call the say_hello method
def call_say_hello(person):
person.say_hello()
# Use np.vectorize to call the say_hello method on each person
vectorized_func = np.vectorize(call_say_hello)
vectorized_func(people)
```
Output:
```
Hello, my name is John
Hello, my name is Jane
Hello, my name is Bob
```
In this example, we create a NumPy array of `Person` instances. We define a function `call_say_hello` that calls the `say_hello` method on a `Person` instance. We then use `np.vectorize` to apply this function to each element of the `people` array and call the `say_hello` method on each `Person` object.
阅读全文