[Tutor] pointers for python?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Oct 6 20:02:33 EDT 2003


> >def inc(x):
> >	x+=1
> >
> >a=1
> >inc(a)
> >print a
> >
> >prints "1"
> >
> >is there a way to get the inc() function to modify the original
> >variable, even though it's not in the function's scope?

Hello!

Not this way.  This may seem like a limitation, but it's consistant and
forces Python functions to be more useful for arbitrary expressions.
This isn't obvious, so let's talk about it a little more.



What should happen if we do something like this?

    inc(42)      ## what happens here?


Since you're familiar with C/C++, let's use a C++ example:

///
using namespace std;

#include <iostream>

// Increments reference variable x.
void inc(int &x) {
  x++;
}

int main() {
  int number = 42;
  inc(number);
  cout << number << endl;
  //   inc(42);    <-- this won't work!
}
///

The commented-out line actually doesn't work --- it's a compile-time error
--- because our inc() definition above can only work with variables.


If we have to think about references, we now have to make this weird
distinction between expressions and variables.  So the reference-passing
model --- distinguishing between references and values --- is just more
unnecessarily involved than the simpler pass-by-value system in Python.



Hope this helps!




More information about the Tutor mailing list