Training, Open Source computer languages

PerlPHPPythonMySQLhttpd / TomcatTclRubyJavaC and C++LinuxCSS

Search our site for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Please visit
http://www.wellho.net/solutions/python-copying-an-object-copy-the-reference.html
for the latest update to this page
copying an object - copy the reference

I call my father "Dad" but everyone else calls him "Norman". Same person, different name.

If Dad puts on the hat that he's got from the Christmas cracker before he eats his Christmas pudding, then everyone else sees that Norman has put on his hat before eating his Christmas pudding. Two names for one and the same person.

PYTHON - COPY BY REFERENCE

The same principle applies to the copying of objects in Python (and Java and PHP 5 and other object oriented languages); an assignment statement is just the addition of an extra name to the same object.

Let's see an example - in Python:

pie = ["apple","pear","strawberry"]
pudding = pie
pudding[1] = "apricot"
print pudding
print pie

When I run that:

earth-wind-and-fire:~/feb05 grahamellis$ python obcop.py
['apple', 'apricot', 'strawberry']
['apple', 'apricot', 'strawberry']
earth-wind-and-fire:~/feb05 grahamellis$

By changing "pudding" I've also changed "pie".

PERL - COPY BY CONTENTS

In contrast, if I copy a list in Perl (and in PHP 4, Tcl and other languages which are not 100% object oriented), I duplicate the data. Example in Perl:

@pie = ("apple","pear","strawberry");
@pudding = @pie;
$pudding[1] = "apricot";
print "@pudding\n";
print "@pie\n";

Which runs:

earth-wind-and-fire:~/feb05 grahamellis$ perl obcop.pl
apple apricot strawberry
apple pear strawberry
earth-wind-and-fire:~/feb05 grahamellis$


See also Python programming course

Please note that articles in this section of our web site were current and correct to the best of our ability when published, but by the nature of our business may go out of date quite quickly. The quoting of a price, contract term or any other information in this area of our website is NOT an offer to supply now on those terms - please check back via our main web site
Related Material

Python - More on Collections and Sequences
Object Oriented Python
resource index - Python
Solutions centre home page

You'll find shorter technical items at The Horse's Mouth and delegate's questions answered at the Opentalk forum.

At Well House Consultants, we provide training courses on subjects such as Ruby, Perl, Python, Linux, C, C++, Tcl/Tk, Tomcat, PHP and MySQL. We're asked (and answer) many questions, and answers to those which are of general interest are published in this area of our site.


WELL HOUSE CONSULTANTS LTD.: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 0800 043 8225 or 01225 708225 • FAX: 0845 8382 405 or 01225 707126 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho