Finding the instance reference of an object
fuzzyman at gmail.com
Thu Oct 23 00:05:40 CEST 2008
On Oct 17, 10:39 pm, Joe Strout <j... at strout.net> wrote:
> On Oct 17, 2008, at 3:19 PM, Grant Edwards wrote:
> >> And my real point is that this is exactly the same as in every
> >> other modern language.
> > No, it isn't. In many other languages (C, Pascal, etc.), a
> > "variable" is commonly thought of as a fixed location in memory
> > into which one can put values. Those values may be references
> > to objects.
> Right, though not in languages like C and Pascal that don't HAVE the
> notion of objects. We really ought to stop bringing up those
> dinosaurs and instead compare Python to any modern OOP language.
> > In Python, that's not how it works. There is no
> > "location in memory" that corresponds to a variable with a
> > particular name the way there is in C or Pascal or Fortran or
> > many other languages.
> No? Is there any way to prove that, without delving into the Python
> source itself?
.NET makes a clear distinction between 'value types' and reference
types. These are analagous to the call by value and call by reference
that have been discussed in this thread.
My understanding of the difference is that value types (all numeric
types, structs, enumerations etc) actually live on the stack, whereas
reference types (strings, classes etc) live in the heap and have a
pointer on the stack.
It is complicated by the fact that .NET perpetuates the myth that the
primitives (the value types) inherit from System.Object (a reference
type). The runtime does auto-boxing for you where this matters.
This means that when you pass a value type into a method the value
*is* copied. Structs can be arbitrarily big, so this can be a
performance problem. It is often a performance win for working with
the numeric types as you remove a level of indirection.
It isn't without problems though - and some of these can be seen in
System.Drawing.Point is a struct, but it is effectively a mutable
value type. However, when you access it you are often accessing a copy
- and if you attempt to mutate it then your changes will be lost.
The following code illustrates the problem:
>>> r = Rectangle(0, 1002 20, 40)
>>> r.Location.X = 20
Because r.Location returns a value type, the update to it is 'lost'.
By this definition Python objects (all of them) are clearly reference
types and not value types.
In .NET you can specify that a parameter to a method takes a reference
('out' in C# or ByRef in VB.NET). If you pass in a value type as a
reference parameter then the .NET runtime will do boxing / unboxing
This means that we can write code like the following (roughly C#
int x = 3;
x can now be mutated by 'SomeMethod' and can have a different value.
In a 'way' immutable Python types behave a bit like .NET value types,
and mutable types like reference types. As you can see, this analogy
More information about the Python-list