Introductory Programming Fall 2004 Python Objects -------------- Big ideas: 0) the most basic use of objects is to collect related data in a single unit Example: a Point object contains coordinates 1) defining a new class defines a new type of object 2) then you can create new objects with the new type Try the following tests in a Python interpreter: 1) Create a new class >>> class Point: pass Creating a class creates a "class object" >>> print Point __main__.Point >>> print type(Point) 2) Use the class object to create instances of the class. >>> p = Point() p now refers to a Point object >>> print p <__main__.Point instance at 0xf6f7678c> >>> print type(p) Common error: what happens if you forget the () ? >>> p = Point >>> print p 3) Add attributes to an object >>> p.x = 100 >>> p.y = 200 >>> print p.x, p.y 100 200 The Point named p contains two pieces of data, named x and y. What does the state diagram look like? 4) More than one variable can refer to the same object >>> q = p What does the state diagram look like now? If you change "q", you are also changing "p", because q and p are aliases for the same object. >>> q.x = 300 >>> print p.x, p.y 300 200 5) How do we know that p and q are the same object? >>> id(p) -151558260 >>> id(q) -151558260 6) The copy module provides functions for copying objects: >>> import copy >>> r = copy.copy(q) 7) The is operator tells you whether two variables refer to the same object >>> p is q >>> p is r >>> q is r 8) For user-defined classes, the == operator is the same as is. >>> p == q >>> p == r >>> q == r But we will revisit this operator later! Amoeba redux ------------ Type the following program into a file named amoeba.py from World import * from time import sleep world = AmoebaWorld() amy = Amoeba(world) for i in range(10): amy.redraw(i, i) world.update() sleep(0.5) world.mainloop() So you can move Amoebas around by invoking redraw with the new coordinates, but in general, Amoebas don't know where they are! (notice that redraw is a method you invoke on an Amoeba) Add code so that each time the Amoeba moves, it stores the new x and y coordinates as attributes of the Amoeba. Now check out the teleport function in ip_hw05_soln.py def teleport(a, x, y): # move amoeba a to the given location a.x = x a.y = y a.redraw(a.x, a.y) A couple of things happening here: 1) you can pass objects as parameters 2) the parameter is a temporary alias for the object 3) if you change the object in a function, the object stays changed (unlike local variables, which disappear when the function ends) One more time, draw a state diagram that shows this effect.