On Fri, May 16, 2008 at 1:48 PM, David MacQuigg
<macquigg at ece.arizona.edu> wrote:
> In Python, there is only one way to pass an argument. There may be pointers flying around, but we never see them. We will have to infer what is going on by doing some tests. Again, the model and terminology for our discussion is:
Sounds like you're wanting to dig into the C, Java or C# code to see
Python's implementation?
PyObject is going to be a big blip on your radar then.
I like Guido's quick overview at Stanford by the way, just to give
students some context:
http://www.stanford.edu/class/cs242/slides/2006/python-vanRossum.ppt
(a Powerpoint).
While you're working on this, you might want to remind your C students
to think of functions as objects as well (everything is an object) and
therefore passable as parameters, just like other objects. Not every
C programmer will expect this, so a heads up.
In the example below, we change the documentation string on one of our
functions:
>>> def f(x):
"""docs"""
pass
>>> def g( thefunc ):
thefunc.func_doc = "hey, different!"
>>> f.func_doc
'docs'
>>> g( f )
>>> f.func_doc
'hey, different!'
>>>
Same pass-by-value of a reference idea, but to a function type this time.
>>> type(f)
<type 'function'>
Of course we can propagate function references using the assignment
operator, per usual:
>>> r = f
>>> r
<function f at 0x00E4FC30>
>>> r is f
True
The verbs "to call" and "to pass" are similar, such that r = f is passing
a reference whereas g ( f ) is calling a reference and passing an argument
(by value, in the sense that thefunc, a local name, adds to the underlying
PyObject's reference count, i.e. it copies f's reference to PyObject,
changing PyObject in the process (just a little)).
>>> import sys
>>> sys.getrefcount( f )
3
>>> del r
>>> sys.getrefcount( f )
2
>>> h = f
>>> sys.getrefcount( f )
3
Trying to think why the refcount jumps to 5 when I check it inside g:
>>> h = f
>>> sys.getrefcount( f )
3
>>> def g(thefunc):
thefunc.func_doc = "hey, different!"
print sys.getrefcount(thefunc)
>>> g(h)
5
>>> sys.getrefcount(h)
3
Clues anyone? I'm not much of an under-the-hood guy.
Kirby