Consider the following Python class that implements the __array__ method. What will be the output when converting an instance to a NumPy array?
import numpy as np class MyArray: def __array__(self): return np.array([10, 20, 30]) obj = MyArray() result = np.array(obj) print(result)
The __array__ method returns a NumPy array representation of the object. NumPy uses this to create the array.
The __array__ method returns a 1D NumPy array [10, 20, 30]. When np.array(obj) is called, it uses this method to get the array data. So the output is a 1D array printed as [10 20 30].
Given this class with a __array__ method, what is the shape of the resulting NumPy array?
import numpy as np class Custom: def __array__(self): return np.array([[1, 2], [3, 4], [5, 6]]) obj = Custom() arr = np.array(obj) print(arr.shape)
Look at the shape of the array returned inside __array__.
The __array__ method returns a 2D array with 3 rows and 2 columns, so the shape is (3, 2).
Examine the code below. Why does calling np.array(obj) raise an error?
import numpy as np class Broken: def __array__(self): return [1, 2, 'three'] obj = Broken() np.array(obj)
NumPy can create arrays from lists with mixed types by upcasting to strings.
The __array__ method returns a list with mixed types. NumPy converts this to an array of strings automatically, so no error occurs. The output is array(['1', '2', 'three'], dtype='
Choose the best description of what the __array__ method does in a Python object used with NumPy.
Think about how NumPy uses this method internally.
The __array__ method tells NumPy how to get an array representation of the object. When np.array() is called on the object, NumPy calls this method to get the data.
Given the class below, what will be the output of np.array(obj)?
import numpy as np class Wrapper: def __init__(self, data): self.data = data def __array__(self, dtype=None): arr = np.array(self.data) if dtype: return arr.astype(dtype) return arr * 2 obj = Wrapper([1, 2, 3]) result = np.array(obj, dtype=np.float64) print(result)
The __array__ method can accept a dtype argument to customize conversion.
The __array__ method receives the dtype=np.float64 argument from np.array(). It converts self.data to an array [1 2 3], then since dtype is truthy, returns arr.astype(np.float64), resulting in [1. 2. 3.]. The multiplication by 2 only occurs if no dtype is specified.