Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
 
For 2023 (and 2024 ...) - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))
Everything is an object

Posted by admin (Graham Ellis), 14 January 2005
In Python, everything's an object.  Might seem odd at first, but the more you get to know it the more clear and logical it is.  Even methods are named objects!

Have a look at this example piece of code:

Code:
source = ["apple","orange","banana","pear"]
c1cat = c1dog = []
c2cat = c2dog = []

print "Using the + Operator"
for thing in source:
       c1cat = c1cat + [thing]
       c1dog = c1dog + [thing]
print c1cat
print c1dog

print "Using the += assignment"
for thing in source:
       c2cat += [thing]
       c2dog += [thing]
print c2cat
print c2dog


And when it runs, you get:

Code:
dolphin:/Library/WebServer/live_cgi-bin/net/py05 graham$ python obc
Using the + Operator
['apple', 'orange', 'banana', 'pear']
['apple', 'orange', 'banana', 'pear']
Using the += assignment
['apple', 'apple', 'orange', 'orange', 'banana', 'banana', 'pear', 'pear']
['apple', 'apple', 'orange', 'orange', 'banana', 'banana', 'pear', 'pear']
dolphin:/Library/WebServer/live_cgi-bin/net/py05


Why is everything doubled when you use the += operator?  

Objects explain in all.

In the first case, a new object is created each time something is added onto the end of the previous list.  But in the second case, something is added onto the end of the existing list in the loop; since c2cat and c2dog are just two different names for the same object, that something added is added twice.



This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2024: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho