Difference between revisions of "CSC111 Simple Programs Introducing OOP"

From dftwiki3
Jump to: navigation, search
(Output)
 
Line 184: Line 184:
 
<br />
 
<br />
 
<br />
 
<br />
<onlydft>
+
 
 
=Dogs=
 
=Dogs=
 
<br />
 
<br />
Line 249: Line 249:
 
main()
 
main()
 
</source>
 
</source>
</onlydft>
+
 
 
<br />
 
<br />
 +
<onlydft>
 +
=A Class that holds a List of Person Objects=
 
<br />
 
<br />
 +
<source lang="python">
 +
# peopleOOP2.py
 +
# D. Thiebaut
 +
# Collection of People (mirror of Program peopleNOOOP.py)
 +
# A preparation program for Object Oriented programming.
 +
# This program USES OBJECTS.  It creates a list
 +
# of people composed of a name, an age, a gpa, and a major.
 +
# It displays the partial list of the people, add a new person,
 +
# modifies one record, and displays the new partial list.
 +
 +
text = """
 +
Alex, 20, 3.6, ART
 +
Lulu, 21, 3.5, BIO
 +
Alka, 19, 3.0, ENG
 +
Le, 21, 3.2, EGR
 +
"""
 +
 +
# ____                         
 +
#|  _ \ ___ _ __ ___  ___  _ __ 
 +
#| |_) / _ \ '__/ __|/ _ \| '_ \
 +
#|  __/  __/ |  \__ \ (_) | | | |
 +
#|_|  \___|_|  |___/\___/|_| |_|
 +
#
 +
class Person:
 +
    # a class containing 4 fields:
 +
    # - name of the person (string)
 +
    # - age (integer)
 +
    # - gpa (float)
 +
    # - major (string, uppercase)
 +
 +
    # constructor: intializes a person with all fields
 +
    def __init__(self, n, a, g, m):
 +
        self._name = n
 +
        self._age  = a
 +
        self._gpa  = g
 +
        self._major= m
 +
 +
    # returns a string with the name and age.
 +
    def toString( self ):
 +
        return "\t%s\t\t%d" % ( self._name, self._age )
 +
 +
    def __str__( self ):
 +
        return "\t%s\t\t%d" % ( self._name, self._age )
 +
 +
    # returns the name
 +
    def getName( self ):
 +
        return self._name
 +
 +
    # set the age to a new value x
 +
    def setAge( self, x ):
 +
        self._age = x
 +
 +
    # returns the age of the person
 +
    def getAge( self ):
 +
        return self._age
 +
 +
# ____                  _      _    _    _ 
 +
#|  _ \ ___  ___  _ __ | | ___| |  (_)___| |_
 +
#| |_) / _ \/ _ \| '_ \| |/ _ \ |  | / __| __|
 +
#|  __/  __/ (_) | |_) | |  __/ |___| \__ \ |_
 +
#|_|  \___|\___/| .__/|_|\___|_____|_|___/\__|
 +
#                |_|
 +
#
 +
class PeopleList:
 +
    # PeopleList: a class containing a list of people
 +
    # defined as objects of type Person.
 +
    # Methods supported:
 +
    #    constructor: creates an empty list
 +
    #    append( Person): adds a new person to list
 +
    #    isEmpty():  returns True if list empty, False otherwise
 +
    #    size():    returns the number of people in list
 +
    #    getPerson(name): returns the person whose name is specified
 +
    #                or None if person not found
 +
    #    display():  displays contents of list.  Uses default display
 +
    #                method for Person objects inside list.
 +
    #    buildFromText(text): parses text, one person per line, and
 +
    #                add valid lines as Person objects to list.
 +
   
 +
    # constructor
 +
    def __init__( self ):
 +
        self._List = []
 +
 +
    # add a new person object to the list
 +
    def append( self, p ):
 +
        self._List.append( p )
 +
       
 +
    # returns the # items in list
 +
    def size( self ):
 +
        return len( self._List )
 +
 +
    # returns True if list empty
 +
    def isEmpty( self ):
 +
        return len( self._List )==0
 +
 +
    # returns person matching name.  None otherwise.
 +
    def getPerson( self, name ):
 +
        for person in self._List:
 +
            if person.getName().lower() == name.lower().strip():
 +
                return person
 +
        return None
 +
 +
    # prints contents of list
 +
    def display( self ):
 +
        for person in self._List:
 +
            print( person )
 +
 +
    # returns string representing list.
 +
    def __str__( self ):
 +
        s = ""
 +
        for person in self._List:
 +
            s += person.__str__() + "\n"
 +
        return s
 +
 +
    # buildFromText: parse text and create Person objects
 +
    def buildFromText( self, text ):
 +
        for line in text.split( "\n" ):
 +
            words = line.split( "," )
 +
       
 +
            # skip ill-formed lines
 +
            if len( words ) != 4:
 +
                continue
 +
       
 +
            # strip each word
 +
            words = [ w.strip() for w in words ]
 +
 +
            person = Person( words[0], int( words[1] ), float( words[2] ), words[3] )
 +
            self._List.append( person )
 +
 +
 +
def main():
 +
    #
 +
    L = PeopleList()
 +
 +
    # add people to list
 +
    L.buildFromText( text )
 +
 +
    # display contents of lst
 +
    print( L )
 +
 +
    # add a new person to the list
 +
    L.append( Person("Xiaole", 21, 3.9, "CSC") )
 +
 +
    # modify age of person named Alka
 +
    name = "Alka"
 +
    p = L.getPerson( name )
 +
    if p==None:
 +
        print( name, "not found in list" )
 +
    else:
 +
        p.setAge( p.getAge() + 1 )
 +
 +
    print( L )
 +
 +
# This version of main() is the older version, and uses a
 +
# Python list to hold the people objects.
 +
def mainOld():
 +
    # create a list of people taken from the text
 +
    people = []
 +
    for line in text.split( "\n" ):
 +
        words = line.split( "," )
 +
       
 +
        # skip ill-formed lines
 +
        if len( words ) != 4:
 +
            continue
 +
       
 +
        # strip each word
 +
        words = [ w.strip() for w in words ]
 +
 +
        person = Person( words[0], int( words[1] ), float( words[2] ), words[3] )
 +
        people.append( person )
 +
 +
    # display the list of names and their age
 +
    print( "Names: " )
 +
    for person in people:
 +
        print( person.asString() )
 +
 +
    # add a new person to the list
 +
    people.append( Person("Xiaole", 21, 3.9, "CSC") )
 +
 +
    # modify age of person named Alka
 +
    for person in people:
 +
        if person.getName().lower() == "alka":
 +
            person.setAge( person.getAge() + 1 )
 +
 +
    # display the list of names and their age
 +
    print( "Names: " )
 +
    for person in people:
 +
        print( person.asString() )
 +
 +
   
 +
main()
 +
 +
 +
       
 +
 +
</source>
 
<br />
 
<br />
 +
</onlydft>
 
<br />
 
<br />
 
<br />
 
<br />

Latest revision as of 10:23, 11 April 2014

--D. Thiebaut (talk) 10:00, 7 April 2014 (EDT)



Program 1: NO OOP


# peopleNOOOP.py
# D. Thiebaut
# Collection of People.
# A preparation program for Object Oriented programming.
# This program DOES NOT USE OBJECTS.  It creates a list
# of people composed of a name, an age, a gpa, and a major.
# It displays the partial list of the people, add a new person,
# modifies one record, and displays the new partial list.

text = """
Alex, 20, 3.6, ART
Lulu, 21, 3.5, BIO
Alka, 19, 3.0, ENG
Le, 21, 3.2, EGR
"""

def main():
    # create a list of people taken from the text
    people = []
    for line in text.split( "\n" ):
        words = line.split( "," )
        # skip ill-formed lines
        if len( words ) != 4:
            continue
        # strip each word
        words = [ w.strip() for w in words ]
        person = [ words[0], int( words[1] ), float( words[2] ), words[3] ]
        people.append( person )

    # display the list of names and their age
    print( "Names: " )
    for name, age, gpa, major in people:
        print( "\t", name, "\t\t", age )

    # add a new person to the list
    people.append( [ "Xiaole", 21, 3.9, "CSC" ] )

    # modify age of person named Alka
    for person in people:
        if person[0].lower() == "alka":
            person[1] += 1

    # display the list of names
    print( "Names: " )
    for name, age, gpa, major in people:
        print( "\t", name, "\t\t", age )
            
    
main()


Output


Names: 
	 Alex 		 20
	 Lulu 		 21
	 Alka 		 19
	 Le 		 21
Names: 
	 Alex 		 20
	 Lulu 		 21
	 Alka 		 20
	 Le 		 21
	 Xiaole 		 21


Same Program, using OOP


# peopleOOP.py
# D. Thiebaut
# Collection of People (mirror of Program peopleNOOOP.py)
# A preparation program for Object Oriented programming.
# This program USES OBJECTS.  It creates a list
# of people composed of a name, an age, a gpa, and a major.
# It displays the partial list of the people, add a new person,
# modifies one record, and displays the new partial list.

text = """
Alex, 20, 3.6, ART
Lulu, 21, 3.5, BIO
Alka, 19, 3.0, ENG
Le, 21, 3.2, EGR
"""

class Person:
    # a class containing 4 fields:
    # - name of the person (string)
    # - age (integer)
    # - gpa (float)
    # - major (string, uppercase)

    # constructor: intializes a person with all fields
    def __init__(self, n, a, g, m):
        self._name = n
        self._age  = a
        self._gpa  = g
        self._major= m

    # returns a string with the name and age.
    def toString( self ):
        return "\t%s\t\t%d" % ( self._name, self._age )

    # returns the name
    def getName( self ):
        return self._name

    # set the age to a new value x
    def setAge( self, x ):
        self._age = x

    # returns the age of the person
    def getAge( self ):
        return self._age


def main():
    # create a list of people taken from the text
    people = []
    for line in text.split( "\n" ):
        words = line.split( "," )
        
        # skip ill-formed lines
        if len( words ) != 4:
            continue
        
        # strip each word
        words = [ w.strip() for w in words ]

        person = Person( words[0], int( words[1] ), float( words[2] ), words[3] )
        people.append( person )

    # display the list of names and their age
    print( "Names: " )
    for person in people:
        print( person.toString() )

    # add a new person to the list
    people.append( Person("Xiaole", 21, 3.9, "CSC") )

    # modify age of person named Alka
    for person in people:
        if person.getName().lower() == "alka":
            person.setAge( person.getAge() + 1 )

    # display the list of names and their age
    print( "Names: " )
    for person in people:
        print( person.toString() )

main()


Output


Names: 
	Alex		20
	Lulu		21
	Alka		19
	Le		21
Names: 
	Alex		20
	Lulu		21
	Alka		20
	Le		21
	Xiaole		21



Dogs


# dogs.py
# D. Thiebaut
# An OOP program illustrating the use of another class, and 
# creating a list of objects created from this class.


# DOG: a class providing a container for a tag name and a 
# boolean indicating if the dog is vaccinated or not.
# public methods supported:
#  - isVaccinated() return True if the dog is, False otherwise
#  - getNameTag() returns the dog's name tag
#  - setNameTag() sets the name tag to the string argument
#  
class Dog:

    # constructor
    def __init__( self, tag, vaccinated ):
        self._tag = tag
        self._vaccinated = vaccinated

    # default string representation for the dog
    def __str__( self ):
        if self._vaccinated==True:
            return "%s (vaccinated)" % self._tag
        return "%s (not vaccinated)" % self._tag

    def isVaccinated( self ):
        return self._vaccinated

    def getNameTag( self ):
        return self._tag

    def setNameTag( self, tag ):
        self._tag = tag

# displays a list of dogs
def displayList( list, caption ):
    print( caption )
    for dog in list:
        print( dog )
    
# main program: creates a list of dogs, displays it, finds the vaccinated ones.
def main():
    dogs = []

    dogs.append( Dog( "Rex", True ) )
    dogs.append( Dog( "Fido", False ) )
    dogs.append( Dog( "Fifi", True ) )

    displayList( dogs, "\n\nList of dogs" )
    
    vaccinated = []
    for dog in dogs:
        if dog.isVaccinated():
            vaccinated.append( dog )

    displayList( dogs, "\n\nList of vaccinated dogs" )
    
    
main()



...