Difference between revisions of "CSC111 Simple Programs Introducing OOP"

From dftwiki3
Jump to: navigation, search
(Same Program, using OOP)
(Output)
Line 184: Line 184:
 
<br />
 
<br />
 
<br />
 
<br />
 +
<onlydft>
 +
=Dogs=
 
<br />
 
<br />
 +
<source lang="python">
 +
# 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()
 +
</source>
 +
</onlydft>
 
<br />
 
<br />
 
<br />
 
<br />

Revision as of 09:01, 9 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




...