0
0
NumPydata~15 mins

Array protocol and __array__ in NumPy - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Array Protocol and __array__ Method in NumPy
📖 Scenario: Imagine you have a custom class that stores data like a list, but you want to use NumPy functions on it easily. NumPy can convert objects to arrays if they follow the array protocol by implementing the __array__ method.
🎯 Goal: You will create a simple custom class with a __array__ method so that NumPy can convert it to an array. Then, you will use NumPy functions on your custom object.
📋 What You'll Learn
Create a custom class called MyData that stores a list of numbers.
Add a __array__ method to MyData that returns a NumPy array of the stored data.
Create an instance of MyData with specific numbers.
Use np.array() to convert the MyData instance to a NumPy array.
Print the resulting NumPy array.
💡 Why This Matters
🌍 Real World
Custom data classes can store data in special ways but still work with NumPy functions by implementing the array protocol.
💼 Career
Understanding the array protocol helps you integrate your own data structures with NumPy, a key skill in data science and scientific computing.
Progress0 / 4 steps
1
Create the MyData class with stored data
Create a class called MyData with an __init__ method that takes a list called data and stores it in self.data. Then create an instance called my_data with the list [10, 20, 30].
NumPy
Need a hint?

Define a class with __init__ to save the list in self.data. Then create an object my_data with the list [10, 20, 30].

2
Add the __array__ method to MyData
Inside the MyData class, add a method called __array__ that takes self, dtype=None and returns np.array(self.data, dtype=dtype). Make sure to import NumPy as np at the top.
NumPy
Need a hint?

The __array__ method should take self, dtype=None and return np.array(self.data, dtype=dtype).

3
Convert my_data to a NumPy array using np.array()
Create a variable called array_version and set it to np.array(my_data) to convert the MyData instance to a NumPy array.
NumPy
Need a hint?

Use np.array(my_data) to get the NumPy array from your custom object.

4
Print the NumPy array array_version
Write a print statement to display the variable array_version.
NumPy
Need a hint?

Use print(array_version) to show the NumPy array.