rougier / numpy-100

100 numpy exercises (with solutions)
MIT License
12.17k stars 5.74k forks source link

An alternative solution for Q.63 (Typo) #172

Closed lots-o closed 2 years ago

lots-o commented 2 years ago

The task is as follows : Create an array class that has a name attribute

The solution is as follows :

class NamedArray(np.ndarray):
    def __new__(cls, array, name="no name"):
        obj = np.asarray(array).view(cls)
        obj.name = name
        return obj
    def __array_finalize__(self, obj):
        if obj is None: return
        self.info = getattr(obj, 'name', "no name") 

Z = NamedArray(np.arange(10), "range_10")
print (Z.name)

An alternative solution will be :

class NamedArray(np.ndarray):
    def __new__(cls, array, name="no name"):
        obj = np.asarray(array).view(cls)
        obj.name = name
        return obj
    def __array_finalize__(self, obj):
        if obj is None: return
        self.name = getattr(obj, 'name', "no name") #Modify typo

Z = NamedArray(np.arange(10), "range_10")
print (Z.name)
rougier commented 2 years ago

You're right, thanks. Can you make a PR?