Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object is changed in Python

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) ?

like image 431
PKumar Avatar asked Aug 15 '26 04:08

PKumar


1 Answers

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:

  • NumPy mathematical functions
  • np.take()
  • np.choose()
  • np.compress()
  • Most of NumPy's logic functions

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:

  • ndarray.sort()

Some functions and methods do not use the out parameter, returning a memory view whenever possible:

  • function 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
like image 131
Saullo G. P. Castro Avatar answered Aug 16 '26 18:08

Saullo G. P. Castro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!