Parameters passing in Python

K

kk

When I learnt Java, I was told that for its primitive types, parameter
passing is done by value. For objects, by reference.
I started to learn Python months ago, but I still can't figure out the
parameter passing style of Python. List, Dict, Object...
When I search in mailing list, I found that someone raised the same
question and someone responded Python uses 'pass by object'.
Would anyone explain a bit more in detail?
Thank you in advance.
 
A

Alex Martelli

kk said:
When I learnt Java, I was told that for its primitive types, parameter
passing is done by value. For objects, by reference.

With Python, always "by object reference". Of course, for immutable
types (strings, numbers) it makes no real difference!
I started to learn Python months ago, but I still can't figure out the
parameter passing style of Python. List, Dict, Object...
When I search in mailing list, I found that someone raised the same
question and someone responded Python uses 'pass by object'.
Would anyone explain a bit more in detail?

Just like in Java to all intents and purposes. You get a reference
to the object (NOT to the name, aka variable, that may refer to that
object). If the object is immutable (string, number, tuple) that's
just like receiving a copy of the value -- there is no copy -- it's
the original value -- but you don't care since nothing can change it
anyway. If the object is mutable (list, dict, instances of most
usercoded classes) then it IS important that no copy is implicitly
made (just as no copy is implicitly made in java) since you can
mutate the object (append to a list, etc etc) and what will be
mutated is "the original" that was passed. If you WANT a copy you
explicitly ask for one (most generally via standard module copy).


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,460
Latest member
eibafima

Latest Threads

Top