Newbie question. Are those different objects ?

rurpy at yahoo.com rurpy at yahoo.com
Fri Dec 20 13:06:57 EST 2013


On 12/20/2013 08:16 AM, dec135 at msn.com wrote:
> y = raw_input('Enter a number:')
> print type y
> y = float(raw_input('Enter a number:'))
> print type y
> 
> I'm assuming that y is an object.

Rather than thinking that y "is" an object, it is more accurate
to think of it as: y is a name that is "bound" to (ie, refers to, 
points to) an object.

So, raw_input() creates a string object and returns it.  Your 
first assignment statement binds that string object to the name
"y".  From now on, when you refer to "y" you will get that
string object.

When python executes your 3rd line, raw_input() creates a new
string object, completely separate from the earlier one.  This
object is passed to float().  Float() reads it and creates a
new float object and returns it.  When python then executes 
your second assignment statement, it changes the binding of "y"
to point to the float object; the old binding to the string 
object is lost.  From now on, when you refer to "y" you will 
get the float object.

> I'm also assuming that the second and the first y are different
> objects because they have different types. 

Yes, they are different objects.  But not because they have 
different types; they are different because every time python
creates a new object it is distinct from other objects [*1].

> The second time we type
> print type y, how does the program knows which one of the y's it
> refers to ?  

Because there is only one name "y", and when python executed
your second assignment statement, it changed the object that
the name y pointed to from the first (string) object to the 
second (float) one.

> Is the first y object deleted ? thanks in advance.

Yes.  If there is no way that the first object can be accessed 
any more, then it will be deleted.  The same thing happened to 
the string object return by raw_input() in your 3rd statement
(which never had a name at all).

----
[*1] My statement was an oversimplification.  There are some 
cases where Python will return the same object such as interned
objects and objects like None for which there is only ever a 
single instance in a Python program.



More information about the Python-list mailing list