Difference between revisions of "CSC111 Exercise with Class Inheritance"

From dftwiki3
Jump to: navigation, search
 
Line 99: Line 99:
 
<br />
 
<br />
 
<br />
 
<br />
 +
=Solution=
 
<br />
 
<br />
 +
The code below is the code we actually should add above, where the text in purple is located.
 
<br />
 
<br />
 +
<source lang="python">
 +
class PersonWorld( Person ):
 +
    def __init__( self, n, a, g, m, nat ):
 +
        super().__init__( n, a, g, m )
 +
        self._nat = nat
 +
 +
    def __str__( self ):
 +
        s = super().__str__()
 +
        return s +" "+self._nat
 +
</source>
 
<br />
 
<br />
 
<br />
 
<br />

Latest revision as of 12:45, 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.




# personInherited.py
# D. Thiebaut
# A program with a Person class in need of a derived class.
# Name the derive class PersonWorld

 
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


... Add 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()



Solution


The code below is the code we actually should add above, where the text in purple is located.

class PersonWorld( Person ):
    def __init__( self, n, a, g, m, nat ):
        super().__init__( n, a, g, m )
        self._nat = nat

    def __str__( self ):
        s = super().__str__()
        return s +" "+self._nat