4

With a 'normal' Python class I'm used to being able to arbitrarily add extra attributes. For example, I could do the following:

# Create a class
class MyClass: pass

# Create an object of this class
my_object = MyClass()

# Add any attribute I want
my_object.my_new_attribute = "Hello world!"

# Now it has this attribute and I can use it:
print(my_object.my_new_attribute)

This runs without errors and prints Hello world!

However, I seem to be unable to do so with a numpy.ndarray. Consider the following:

# Create an object of the ndarray class:
import numpy as np

my_object = np.array([1,2,3])

# Verify it is indeed of the `numpy.ndarray` type:
print(type(my_object))

# Add a new atribute
my_object.my_new_attribute = "Hello world!"

This outputs <class 'numpy.ndarray'>, verifying we do indeed have an object of some class, but then when trying to add a new attribute we get an error: AttributeError: 'numpy.ndarray' object has no attribute 'my_new_attribute'

Why is this? I understand the error in the sense that numpy.ndarray indeed has no such attribute, but neither did MyClass in the first example and that didn't keep me from being able to just add it.

Lara
  • 2,594
  • 4
  • 24
  • 36
  • `vars(MyClass())` gives `{}`. `vars(np.array([1,2,3]))` gives an error, about a missing `__dict__` artribute. `ndarray` is defined in compiled code with a custom `__new__`. It doesn't have a `__dict__` that can hold user defined attributes. A list has the issue - no `__dict__`. – hpaulj Mar 22 '21 at 16:09
  • See answer https://stackoverflow.com/a/69947072/534674 for why, in general, some classes do not have a `__dict__` attribute. – Jake Stevens-Haas Jun 22 '22 at 20:44

1 Answers1

0

You need to inherit the np.ndarray object and add attributes through the __new__ method. There is a section in the docs on adding an extra attribute to ndarray.

yatu
  • 86,083
  • 12
  • 84
  • 139
  • I guess that's what I'll have to do. It leaves me wondering why I have to jump through this hoop though. – Lara Mar 22 '21 at 12:11