Reputation: 11128
I am newbie to python and OOP concepts and i am unable to understand certain things,like why some function change the original object and some doesn't. To understand it better, I have put my confusion in comments in the below code snippet. Any help is appreciated. Thanks.
from numpy import *
a = array([[1,2,3],[4,5,6]],float)
print a
array([[ 1., 2., 3.],
[ 4., 5., 6.]]) ### Result reflected after using print a
a.reshape(3,2)
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.]]) ### Result reflected on IDE after applying the reshape function
print a
array([[ 1., 2., 3.],
[ 4., 5., 6.]]) ### It remains the same as original value of "a", which is expected.
a.fill(0)
print a
[[ 0. 0. 0.]
[ 0. 0. 0.]] ### It changed the value of array "a" , why?
#############
type(reshape) ### If i try to find the type of "reshape" , i get an answer as "function" .
<type 'function'>
type(fill) ### I get a traceback when i try to find type of "fill", why?
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
type(fill)
NameError: name 'fill' is not defined
My questions are:
1) How do i get to know which function(s)(considering "fill" is a function) are going to change my original object value (in my case its "a") ?
2) Considering(correct me if i am wrong) if "fill" is a function then , why its changing the original value of the object "a" ?
3) Why am I getting a traceback when i use type(fill) ?
Upvotes: 3
Views: 2266
Reputation: 8982
Read the docs or try :)
a.reshape() is a method of object a, same for a.fill(). It can do anything with a. That does not apply for reshape (not a.reshape) - that is a function you've imported from numpy nodule in from numpy import *
.
fill is not in numpy module (you have not imported it), it's a member of the ndarray
object.
Upvotes: 1
Reputation: 58965
A given function can change or not the input object. In NumPy many functions come with an out
parameter, which tells the function to put the answer in this object.
Here are some NumPy functions with the out
parameter:
It may happen that these functions are available as a ndarray
method without the out
parameter, in such case performing the operation in place. Perhaps the most famous is:
Some functions and methods do not use the out
parameter, returning a memory view whenever possible:
np.reshape()
and method ndarray.reshape()
The ndarray.fill()
is one example of subroutine exclusively available as a method, changing the array in-place.
Whenever you get a ndarray object or its subclasses it is possible to check if it is a memory view or not based on the OWNDATA
entry of the flags
attribute:
print(a.flags)
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
Upvotes: 2