DOC PREVIEW
UNI CS 1520 - LECTURE NOTES

This preview shows page 1 out of 3 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 3 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 3 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1. Classes: A class definition is like a blueprint (receipe) for each of the objects of that class A class specifies a set of data attributes and methods for the objects of that class The values of the data attributes of a given object make up its state The behavior of an object depends on its current state and on the methods that manipulate this state The set of a class’s methods is called its interfaceA simple class definition example is a 6-sided Die:"""File: simple_die.pyDescription: This module defines a six-sided Die class."""from random import randintclass Die(object): """This class represents a six-sided die.""" def __init__(self): """The initial face of the die.""" self._currentRoll = randint(1, 6) def roll(self): """Resets the die's value to a random number between 1 and 6.""" self._currentRoll = randint(1, 6) def getRoll(self): """Returns the face value of the die.""" return self._currentRoll def __str__(self): """Returns the string representation of the die.""" return str(self._currentRoll) Consider the following script to test the Die class and its associated output:Classes in Python have the following characteristics: all class attributes (data attributes and methods) are public by default, unless your identifier starts with a singleunderscores, e.g, self._currentRoll  all data types are objects, so they can be used as inherited base classes objects are passed by reference when used as parameters to functions all classes have a set of standard methods provided, but may not work properly (__str__, __doc__, etc.) most built-in operators (+, -, *, <, >, ==, etc.) can be redefined for a class. This makes programming withobjects a lot more intuitive. Data Structures Name:_______________________Lecture 4 Page 1# testDie.py - script to test Die classfrom simple_die import Diedie1 = Die()die2 = Die()print 'die1 =', die1 #calls __str__print 'die2 =', die2printprint 'die1.getRoll() = ', die1.getRoll()print 'die2.getRoll() = ', die2.getRoll()die1.roll()print 'die1.getRoll() = ', die1.getRoll()print 'str(die1): ' + str(die1)print 'die1 + die2:', die1.getRoll() + die2.getRoll()>>> die1 = 2die2 = 5die1.getRoll() = 2die2.getRoll() = 5 die1.getRoll() = 3str(die1): 3die1 + die2: 8>>>Three important features of Object-Oriented Programming (OOP) to simplify programs and make themmaintainable are:1. encapsulation - restricts access to an object's data to its own methods helps to prevent indiscriminant changes that might cause an invalid object state (e.g., 6-side die with a of roll 8)2. inheritance - allows one class (the subclass) to pickup data attributes and methods of other class(es) (the parents) helps code reuse since the subclass can extend its parent class(es) by adding addition data attributes and/ormethods, or overriding (through polymorphism) a parent's methods 3. polymorphism - allows methods in several different classes to have the same names, but be tailored for each class helps reduce the need to learn new names for standard operations (or invent strange names to make them unique)Consider using inheritance to extend the Die class to a generalized AdvancedDie class that can have any numberof sides. The interface for the AdvancedDie class are:Consider the following script and associated output:die1 = Number of Sides=100 Roll=32die2 = Number of Sides=100 Roll=76die3 = Number of Sides=6 Roll=5die1.getRoll() = 32die1.getSides() = 100die1.getRoll() = 70die2.getRoll() = 76die1 == die2: Falsedie1 < die2: Truedie1 > die2: Falsedie1 <= die2: Truedie1 >= die2: Falsedie1 != die2: Truestr(die1): Number of Sides=100 Roll=70die1 + die2: 146Help on class AdvancedDie in moduleadvanced_die:...Data Structures Name:_______________________Lecture 4 Page 2Returns a string representation for the AdvancedDie. Directly as:str(myDie)or indirectly as:print myDie__str__Allows the direct addition of AdvancedDie objects, and returns theinteger sum of their current roll values.sum = myDie + otherDie__add__Allows the comparison operations (>, <, ==, etc.) to work correctly forAdvancedDie objects. if myDie == otherDie:__cmp__Rerolls the die randomly myDie.roll()roll Returns the number of sides on the die myDie.getSides()getSides Returns the current roll of the die myDie.getRoll()getRoll Constructs a die with a specified number of sides and randomly rolls it (Default of 6 sides if no argument supplied)myDie =AdvancedDie(8)__init__Description Example UsageMethod Detail Descriptions of the AdvancedDie Class Methods# testDie.py - script to test AdvancedDie classfrom advanced_die import AdvancedDiedie1 = AdvancedDie(100)die2 = AdvancedDie(100)die3 = AdvancedDie()print 'die1 =', die1 #calls __str__print 'die2 =', die2print 'die3 =', die3print 'die1.getRoll() = ', die1.getRoll()print 'die1.getSides() =', die1.getSides()die1.roll()print 'die1.getRoll() = ', die1.getRoll()print 'die2.getRoll() = ', die2.getRoll()print 'die1 == die2:', die1==die2print 'die1 < die2:', die1<die2print 'die1 > die2:', die1>die2print 'die1 <= die2:', die1<=die2print 'die1 >= die2:', die1>=die2print 'die1 != die2:', die1!=die2print 'str(die1): ' + str(die1)print 'die1 + die2:', die1 + die2help(AdvancedDie)The AdvancedDie class that inherits from the Die superclass. """File: advanced_die.pyDescription: Provides a AdvancedDie class that allows for any number of sidesInherits from the parent class Die in module die_simple"""from simple_die import Diefrom random import randintclass AdvancedDie(Die): """Advanced die class that allows for any number of sides""" def __init__(self, sides = 6): """Constructor for any sided Die that takes an the number of sides as a parameter; if no parameter given then default is 6-sided.""" # call Die parent class constructor Die.__init__(self) self._numSides = sides self._currentRoll = randint(1, self._numSides) def roll(self): """Causes a die to roll itself -- overrides Die class roll""" self._currentRoll = randint(1, self._numSides) def __cmp__(self, rhs_Die): """Overrides the '__cmp__' operator for Dies, to allow for to allow for a deep comparison of two Dice""" if self._currentRoll < rhs_Die._currentRoll: return -1 elif self._currentRoll == rhs_Die._currentRoll: return 0 else: return 1 def __str__(self): """Returns the string representation of the AdvancedDie.""" return 'Number of Sides='+str(self._numSides)+' Roll='+str(self._currentRoll) def __add__(self, rhs_Die): """Returns the sum of


View Full Document

UNI CS 1520 - LECTURE NOTES

Download LECTURE NOTES
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view LECTURE NOTES and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view LECTURE NOTES 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?