Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python object references

I'm aware that in python every identifier or variable name is a reference to the actual object.

a = "hello"
b = "hello"

When I compare the two strings

a == b

the output is

True

If I write an equivalent code in Java,the output would be false because the comparison is between references(which are different) but not the actual objects.

So what i see here is that the references(variable names) are replaced by actual objects by the interpreter at run time.

So,is is safe for me to assume that "Every time the interpreter sees an already assigned variable name,it replaces it with the object it is referring to" ? I googled it but couldn't find any appropriate answer I was looking for.

like image 263
tez Avatar asked Aug 07 '12 02:08

tez


People also ask

Are Python objects passed by reference?

The two most widely known and easy to understand approaches to parameter passing amongst programming languages are pass-by-reference and pass-by-value. Unfortunately, Python is “pass-by-object-reference”, of which it is often said: “Object references are passed by value.”

What is an object reference?

An object reference is information on how to find a particular object. The object is a chunk of main memory; a reference to the object is a way to get to that chunk of memory. The variable str does not actually contain the object, but contains information about where the object is.

What is object reference with example?

A variable whose type is a class contains a reference to an object of the class (i.e., the address of the memory location where the object is allocated). Example: String s; s = "xxx"; The first statement declares a variable s of type String.


1 Answers

If you actually ran that in Java, I think you'd find it probably prints out true because of string interning, but that's somewhat irrelevant.

I'm not sure what you mean by "replaces it with the object it is referring to". What actually happens is that when you write a == b, Python calls a.__eq__(b), which is just like any other method call on a with b as an argument.

If you want an equivalent to Java-like ==, use the is operator: a is b. That compares whether the name a refers to the same object as b, regardless of whether they compare as equal.

like image 113
Danica Avatar answered Oct 20 '22 02:10

Danica