Software Design Lecture Notes Fall 2004 For Friday (which is Monday) 1) Read Chapter 14 2) Do Warmup 6 Leftovers --------- Do the "try this..." examples from notes13.txt 1) list comprehensions 2) DSU pattern 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 Does this mean that objects with the same type don't always have the same attributes? UML State diagrams with objects ------------------------------- Usual way to draw objects is a rectangle with 1) the type of object outside 2) the attributes and their values inside Examples from World.py class World(Gui): def __init__(self): self.animals = [] # other stuff omitted def register(self, animal): self.animals.append(animal) class Turtle(Animal): def __init__(self, world): self.world = world world.register(self) # other stuff omitted Draw a state diagram showing a World with three Turtles. Draw a state diagram showing your data structure from Homework 5. In a stack diagram, the objects can be inside or outside frames. Secret implementation detail ---------------------------- All user-defined objects are really, secretly, internally... DICTIONARIES!!! Try this: class Point: pass blank = Point() blank.x = 100 blank.y = 200 blank.pointless = 'hello' print blank.__dict__ {'y': 200, 'x': 100, 'pointless': 'hello'} A more detailed UML diagram of a user-defined object would show __dict__, but let's not do that.