all_aest
all_aest

Reputation: 33

The internal of numpy ndarray's attributes

I'm using Numpy v1.19. I found that id of some of the ndarray attributes, such as shape and T, vary every time I access them.

For example, id(a.T) and id(a.shape) results in different values in the code below.

>>> import numpy as np
>>> a = np.array(range(12)).reshape(3, 4)
>>> id(a.T)
4510863728
>>> id(a.T)
4537092976
>>> id(a.T)
4514908240
>>> id(a.shape)
4542374664
>>> id(a.shape)
4542475656
>>> id(a.shape)
4542515336

I don't understand this, because if you define a class which has a ndarray or tuple as its attribute, the id will never change. For example:

>>> class A:
...     def __init__(self, tuple):
...         self.tuple = tuple
...
>>> a = A((0, 1, 2))
>>> id(a.tuple)
4339273800
>>> id(a.tuple)
4339273800
>>> id(a.tuple)
4339273800

Why those things happen to ndarray.shape and ndarray.T, and not to A.tuple?

P.S. I've noticed those things can happen if they are defined as @property. Are they?

Upvotes: 1

Views: 83

Answers (1)

user2357112
user2357112

Reputation: 281748

It's not property, but these attributes use the C-level equivalent, a getset descriptor. Getset descriptors run arbitrary code on attribute access, just like properties, and the getset descriptors for these attributes construct new objects.

Upvotes: 1

Related Questions