Difference between revisions of "CSC111 Exercise with Class Inheritance"

From dftwiki3
Jump to: navigation, search
(Created page with "--~~~~ ---- =Exercise= * Transform the program below so that we can keep track of 2 kinds of people, person objects with just a name, age, gpa and major, and person objects ...")
 
Line 109: Line 109:
 
<br />
 
<br />
 
<br />
 
<br />
[[Category:CSC111]][[Category:Python]][[Category:Exercise]]
+
[[Category:CSC111]][[Category:Python]][[Category:Exercises]]

Revision as of 09:43, 18 April 2014

--D. Thiebaut (talk) 10:43, 18 April 2014 (EDT)


Exercise

  • Transform the program below so that we can keep track of 2 kinds of people, person objects with just a name, age, gpa and major, and person objects with a name, an age, a gpa, a major and a country of origin.


# 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.
import sys

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 __str__( self ):
        return "%10s %d (%1.2f)--%s"  % (
             self._name, self._age, self._gpa, self._major )

    # 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

    # gets the GPA
    def getGPA( self ):
        return self._gpa

    # sets the GPA
    def setGPA( self, g ):
        self._gpa = g

... some code here...

def main():
    p = Person( "Alex", 30, 3.99, "ARS" )
    print( p )

    p2 = PersonWorld( "Alka", 35, 3.75, "CSC", "India" )
    print( p2 )
    print( p2.getName(),"had a gpa of", p2.getGPA() )
    
    
main()