pythong referencing/aliasing
Alex Martelli
aleax at aleax.it
Fri Apr 25 12:58:18 EDT 2003
<posted & mailed>
Cameron Laird wrote:
> In article <mailman.1051284819.25791.python-list at python.org>,
> Jeff Epler <jepler at unpythonic.net> wrote:
> .
> [other true stuff]
> .
> .
>>give you a clearer explanation. I can only add one other piece of
>>information: I rarely am hurt by the fact that Python doesn't have
>>references of the type you're talking about.
> .
> .
> .
> I'll make a positive assertion of this: in C and
> C++, stylish programmers frequently use references
Well in C they use POINTERS of course, since references
aren't in the language (they are in C++). And yes, of
course EVERY C programmer uses pointers extensively --
it's hard to write any substantial C program without
such extensive use. In C++, having both references and
pointers, one uses both, for different roles.
> to good effect. Python rarely, very rarely, needs
> to do the same. It might be instructive to choose
> a typical C++ reference idiom, and illustrate how
> its typical use case is better served in Python be
> a derived return, or dictionary construction, or ...
...or direct use of the fact that Python also passes
'references' -- but they're references to VALUES, not
to NAMES. So, a typical C++ use such as:
void transfer_sum(Dollars x, Account& from, Account& onto)
{
from.withdraw(x);
onto.deposit(x);
}
translates right into Python
def transfer_sum(x, from, onto):
from.withdraw(x)
onto.deposit(x)
assuming in each case that a class Account has appropriate
methods withdraw and deposit.
In C++, you have to specify that from and onto are passed
by reference, otherwise you'll get COPIES of the from and
onto objects (if class Account supports copy-assigment at
all, otherwise, more likely, an exception). In Python, you
don't get copies unless you explicitly ask for copies, so
the issue just doesn't arise.
The only C++ usage that needs *translation* is that where
a function ASSIGNS to its by-reference argument. In C++,
variables are "boxes" with values inside -- a reference is
a reference to the "box". In Python, variables are "labels"
("post-it notes") weakly attached to values -- a reference
is a reference to the *value* (there is no such thing as
a "reference to the variable", i.e., "to the NAME").
Java's a lot like Python in this way, incidentally (it has
some complications for a few types, such as numbers, which
use a different assignment and argument-passing approach
than all 'normal' types -- but in practice, since the
equivalent Python types are immutable, Python and Java
behaviors end up being very close anyway in this respect).
Alex
More information about the Python-list
mailing list