Reputation:
what i know in python is i can write something like this
blabla = Classname().somefunctions()
but in this case both the "np.arange" and "reshape" are functions and it confuses me because "np.arange" is a function and is treated like a class. the question is how is this possible??
import numpy as np
a = np.arange(15).reshape(3, 5)
print(a)
Upvotes: 1
Views: 57
Reputation: 509
This happens because np.arange(15)
returns an instance of a class. Actually everything in python are classes. That's why you can for example do "HELLO WORLD".lower()
In this case what the code does is to evaluate np.(arange)
and after reshape(3, 5)
So this will be the equivalent:
import numpy as np
a = np.arange(15)
a = a.reshape(3, 5)
print(a)
Upvotes: 0
Reputation: 996
numpy.arange returns an ndarray
object.
What may have been confusing though is that numpy.reshape is a classmethod that takes an array as an input. However there is an equivalent method numpy.ndarray.reshape that is a method available to ndarray
objects. In your case, it is the latter method that has been used.
Upvotes: 0
Reputation: 36662
I think you are confusing this behavior:
blabla = Classname().somefunctions()
Which is assigning the value returned by calling the method somefunctions()
located in class Classname()
to the variable blabla
with the chaining of two functions in the numpy module:
The first a = np.arange(15)
creates and array of size 15, and assigns it to a variable named a
, and:
the second a.reshape(3, 5)
that reshapes the array a
to an array of 3 arrays containing 5 elements each.
import numpy as np
a = np.arange(15) #-> [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
a = a.reshape(3, 5) #-> [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14]]
print(a)
Upvotes: 0
Reputation: 5070
Python is an object oriented language, where every variable is an object. np.arange
returns ndarray
object. And then, you could call reshape
method of ndarray
object.
import numpy as np
a = np.arange(15)
type(a)
Out[148]: numpy.ndarray
a
Out[149]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
a = a.reshape(3, 5)
type(a)
Out[151]: numpy.ndarray
a
Out[152]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
Upvotes: 1