The meaning of a = b in object oriented languages

Summercool Summercoolness at gmail.com
Tue Sep 18 02:57:36 EDT 2007


On Sep 17, 11:04 pm, Lloyd Linklater <ll... at 2live4.com> wrote:
> SpringFlowers AutumnMoon wrote:
> > Is that the case: if a is an object, then b = a is only copying the
> > reference?
>
> That and it adds a counter.
>
> a = ["foo", "bar"]
> b = a
> b[0] = "bite me"
> p a, b
>
> a = "different"
> p a, b
>
> ***
>
> In the first print, we get
> ["something else", "bar"]
> ["something else", "bar"]
>
> showing that changing b changes a, as expected.  However, if we change
> a, b is NOT changed as seen in the second print.
>
> "different"
> ["something else", "bar"]
>
> That means that there is a counter inside that says to separate the two
> or b would have changed with a as a changed with b initially.

i think the line

a = "different"

means a is now set to a pointer to the String object with content
"different".
or that "a is now a reference to the String object."

and b is still a reference to the Array object.  so that's why a and b
print out different things.  they point to different objects.

i think:

whenever in Ruby, Python, and Java,

a is never an object.  a is always a "reference to an object"...  this
will solve a lot of puzzles when we don't understand some code
behaviors.

when a writing or a book reads "a is a Hash object; a is an Array
object; or a is an Animal object" it is just a short form to say that
"a is a reference to that object."

b = a means "whatever a is referencing to, now b is referencing it
too".

so that's why  a[1] = "foobar"  will change what b will display, but
a = "foobar" will not change what b will display.  (because a[1] =
"foobar" says "what is  a  referencing?  go there and change its
content that has the index 1"  and when b goes there to see it, it is
also changed.)





More information about the Python-list mailing list