Finding the instance reference of an object

Joe Strout joe at strout.net
Fri Oct 17 15:32:18 EDT 2008


On Oct 17, 2008, at 1:03 PM, Aaron Castironpi Brady wrote:

> I'm not fluent in Java so you'll have to be the judge.
>
> In Python:
>
> b= 0
> f( b )
>
> No matter what, b == 0.  C doesn't guarantee this.

It does, unless f's parameter has been declared a reference  
parameter.  (In C++, you'd do this with '&'; I didn't think it was  
possible in C, but it's been a long time since I've used C so maybe it  
is possible nowadays.)

>  Does Java?

Same in Java, and in RB, and in .NET too.  If f's parameter is a by- 
value parameter, then it acts exactly like Python.  (Those languages  
also allow a by-reference parameter declaration, which I think Python  
doesn't allow, but by-value is the default.)

> Further:
>
> b= {}
> c= b
> f( b )
>
> No matter what, 'c is b' is true.

Right, again, this just demonstrates that Python passes values by  
reference.

>  C doesn't have an 'is' operator.

Well, that's literally true, but only because it doesn't have a deep  
equality operator like modern languages.  In C, b and c would be  
pointers, and 'c == b' would be the equivalent of Python's 'c is  
b' (and would be true after the call to f, again assuming you didn't  
go out of your way to declare f with a by-reference parameter).

> Does Java?

Yes.  The behavior's the same.  Same also in every other OOP language,  
as far as I know.

I think all we've established here is that Python always passes  
parameters by value, and in most other languages, passing by value is  
the default (but there's an option to pass by reference if you want).

Python lacks the ByRef-parameter feature, so when that's what you need  
to do, you'd have to wrap your value in some mutable type (like a  
list) and pass that instead.  A little awkward, but no big deal, as  
there are darn few valid reasons to ever pass something by reference  
anyway, especially in a language with tuple packing and unpacking.

Best,
- Joe





More information about the Python-list mailing list