Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How does numpy do this?
#1
Hello,
let me explain what I mean with this example

array = np.array([[2, 0], [5, 9]])  
print(array)           # Result: [[2, 0], [5, 9]]
print(type(array))     # Result: <type 'numpy.ndarray'>
print(array.flatten()) # Result: [2 0 5 9]
So as you can see arrat is a type 'numpy.ndarray' but us returned as a list of lists. I believe that __repr__ and __str__ only allow to change the object representation as a string. Here we get a list and what is really nice is that you can use methods like .flatten() modify it.

I looked into the __new__ help but I didn't get much out of it.
__new__(...)
T.__new__(S, ...) -> a new object with type S, a subtype of T

Can any someone ilustrate with an example a similar behaviour. I've trying without success to mimic that playing with __new__,
but I must be doing something wrong.
Reply
#2
I don't really understand what you mean - array is an ndarray per the result from line 3, as you suggest. You aren't getting Python lists anywhere in that code. print is obviously using the string representation (from the methods you suggest); what else could it do?
Reply
#3
Ok let me explain it with a very simple example then.
I know the following doesn't work but it to shows what I am trying to do.

class Foo(object):
    
    def __new__(cls):
        cls.someVar = 5
        return cls.someVar
    
    def asList():
        return [cls.someVar]
               
f = Foo()   # Resutl: 5
f.asList()  # <-- I would like be able to do this and get: [5]
I get why it doesn't work, because f return an integer and it doesn't have that asList() method. So basically what I meant is if it possible to do what I intended in code above.
Reply
#4
There is missunderstanding

Look this example

import numpy as np 

spam = np.array([[2, 0], [5, 9]])
eggs = [[2, 0], [5, 9]]

#print type
print(type(spam))
print(type(eggs))

# print both
print(spam)
print(eggs)

# compare dir()
print(dir(spam))
print(dir(eggs))
Output:
<class 'numpy.ndarray'> <class 'list'> [[2 0] [5 9]] [[2, 0], [5, 9]] ['T', '__abs__', '__add__', '__and__', '__array__', '__array_finalize__', '__array_function__', '__array_interface__', '__array_prepare__', '__array_priority__', '__array_struct__', '__array_ufunc__', '__array_wrap__', '__bool__', '__class__', '__complex__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imul__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__lshift__', '__lt__', '__matmul__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__xor__', 'all', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'astype', 'base', 'byteswap', 'choose', 'clip', 'compress', 'conj', 'conjugate', 'copy', 'ctypes', 'cumprod', 'cumsum', 'data', 'diagonal', 'dot', 'dtype', 'dump', 'dumps', 'fill', 'flags', 'flat', 'flatten', 'getfield', 'imag', 'item', 'itemset', 'itemsize', 'max', 'mean', 'min', 'nbytes', 'ndim', 'newbyteorder', 'nonzero', 'partition', 'prod', 'ptp', 'put', 'ravel', 'real', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'setfield', 'setflags', 'shape', 'size', 'sort', 'squeeze', 'std', 'strides', 'sum', 'swapaxes', 'take', 'tobytes', 'tofile', 'tolist', 'tostring', 'trace', 'transpose', 'var', 'view'] ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
spam is numpy.ndarray, while eggs is list. when printed they may look similiar, but this is just similiarity in the prinrting representation. As you can see these are instances of different class and they have quite a different attributes.
And when printing ndarray it's not exactly what you show in comment in your code.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(Jun-19-2020, 06:41 AM)rudihammad Wrote: basically what I meant is if it possible to do what I intended in code above
Unfortunately it's not clear what you are trying to do. Is it that you want to have method that returns attributes of a class as list or what?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
oh ok, it was simpler than that sorry. That is what I wanted to do. I just overthought it

class Foo(object):
    
    def __init__(self, someVar):
        self._x = someVar
    
    def asList(self):
        return [self._x]
        
    def asString(self):
        return "'{}'".format(self._x)
     
    def __repr__(self):
        return "{}".format(self._x)
    
foo = Foo(5)    # Result: 5
foo.asList()    # Result: [5] # 
foo.asString()  # Result: '5' # 
I don't know why I thought I would be able to have the constructor return an integer, and then "magically" have methods of that object acting on the integer with a "." operator. It makes absolutly no sense. Never mind. Minor lapsus.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020