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.