Software Design Spring 2008 For today you should have: 1) worked on homework 7 2) prepared for a quiz For next time: 1) work on Homework 7 2) generate project ideas (proposal next Thursday!) Today: 1) quiz 2) class attributes 3) inheritance 4) UML class attributes ---------------- In the Card class, rankList and suitList are class attributes 1) defined inside the class definition, but outside any function 2) there is only one copy of the class attributes as opposed to instance attributes (one per instance) class Card: suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] def __str__(self): return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit]) You can also access class attributes as if they were instance attributes, but I don't think it's a good idea. Representing collections ------------------------ How do we represent a Deck? 1) define a new object type that contains a collection of cards as an attribute. 2) use an "informal data structure" like a list of cards, without defining a new class. Either might be a reasonable choice, but in an object-oriented style, we would tend to favor (1). One reason is that a Deck class is a natural place to keep methods that pertain to Decks, like shuffle, etc. Inheritance ----------- Probably the characteristic feature of object-oriented programming. A new class extends an existing class: class Hand(Deck): def __init__(self, name=''): self.cards = [] self.name = name The new class has all the methods of the old class. The new class can add additional methods, or override existing ones. For example, Hand.__init__ replaces Deck.__init__ Tagger.__init__ overrides Turtle.__init__ but also invokes it: class Tagger(Turtle): def __init__(self, world, speed=1, clumsiness=60, color='red'): Turtle.__init__(self, world) self.delay = 0 self.speed = speed self.clumsiness = clumsiness self.color = color Tagger inherits from Turtle, Turtle inherits from Animal, Animal is a base class -- it inherits from the Ur-object. These chains form a CLASS HIERARCHY. Child classes inherit from parent classes. (or sometimes) Subclasses extend superclasses. UML Class Diagrams ------------------ A UML Class Diagram shows relationships between classes. It is less detailed (more abstract) than an object diagram. Inheritance denotes the IS-A relationship between classes: 1) a Tagger is a kind of Turtle 2) a Turtle is a kind of Animal Embedded objects represent a HAS-A relationship between objects: 1) a Turtle has a reference to a World 2) World has a list of references to Animals 3) a Deck has a list of references to Cards These relationships are shown graphically in a UML Class Diagram. Example: PokerHand wget http://wb/sd/code/PokerHand_lumpy.py python PokerHand_lumpy.py