Software Design Lecture Notes Fall 2004 For Friday: 1) read Chapter 13 and prepare for a quiz on Chapters 12 and 13 Classes ------- Big dose of new vocabulary: class, instance, instantiate, object, constructor, attribute LEARN IT, SPEAK IT, MAKE IT A PART OF YOU. A class is a user-defined type. class Point: pass # later there will be method definitions here class Rectangle: pass Creating a class defines a function with the same name: blank = Point() schmectangle = Rectangle() These functions are called constructors. Invoking a constuctor creates an instance of the class. An instance is a member of a class. An object is something that can be referred to. A reference to an object can be assigned to a variable, passed as an argument or returned as a return value. In Python: All instances are objects (can be referred to...) AND all objects are instances (belong to some class). In casual speech, object and instance are used interchangeably. Attributes ---------- Objects have attributes. An attribute is like a variable that belongs to an object. (recall that a variable is a name that refers to a value) Try this: from World import * world = TurtleWorld() bob = Turtle(world) print bob.x, bob.y print bob.color bob.color = 'blue' print bob.color What color is bob? You can add a new attribute to an object at any time! bob.new_feature = 'whatever you want' print bob.new_feature Stack diagrams with objects --------------------------- Draw a stack diagram for the following program: def find_center(box): p = Point() p.x = blah blah p.y = blah blah return p box = Rectangle() box.width = 100 box.height = 200 box.corner = Point() box.corner.x = 0 box.corner.y = 0 center = find_center(box) Secret implementation detail ---------------------------- All user-defined objects are really, secretly, internally... DICTIONARIES!!! Try this: blank = Point() blank.x = 100 blank.y = 200 blank.pointless = 'hello' print blank.__dict__ {'y': 200, 'x': 100, 'pointless': 'hello'} Now you have to eat this piece of paper. Embedded objects ---------------- Attributes can refer to objects, sometimes called embedded objects. In the book, Rectangles contain an embedded Point object. Objects can share embedded objects, which is yet another form of... Aliasing: 1) two variables refer to the same object 2) a calling function and a called function share references to an object 3) two objects refer to the same embedded object Aliasing is sometimes a good idea, especially if the objects are immutable, but it can spawn DEEP, EVIL BUGS!!!