# calling_methods.py David MacQuigg ece175 5/7/08 ''' How Python does call-by-reference. Python calls are like call-by-reference in C. There is no copying of objects for use as local data. Only pointers get passed to the function. See http://ece.arizona.edu/~edatools/ece175/Lecture/python-variables.htm for more on Python's variables and objects. The caller's object may be modified as long as the local variable retains its binding to that object. In the example below, we add crystals to a MegaLith object owned by the caller. ''' class MegaLith: def __init__(self, x): # special method to intialize an object self.crystals = x def __add__(self, x): # special method to override the + operator self.crystals += x def f(a, b): print "a = %s b = %s" % (a, b.crystals) print id(a), id(b), " original objects" a = a + 1 # a now points to a new object. b + 1 # b still points to the original object. print id(a), id(b), " objects after processing" print "a = %s b = %s" % (a, b.crystals) def main(): ''' >>> main() 9787644 12871520 x = 0 y = 0 a = 0 b = 0 9787644 12871520 original objects 9787632 12871520 objects after processing a = 1 b = 1 x = 0 y = 1 9787644 12871520 ''' x = 0 # a simple integer y = MegaLith(0) # a MegaLith with zero crystals print id(x), id(y) print "x = %s y = %s" % (x, y.crystals) f(x, y) print "x = %s y = %s" % (x, y.crystals) print id(x), id(y) from doctest import testmod testmod(verbose=True)