[Courses] [python] Object-oriented programming

Prana Peddi prana.lists at gmail.com
Tue Aug 2 23:01:51 UTC 2011


Hi Akkana,

I was wondering how to specify inheritance in python - I was planning to use
vehicles, 2 wheeled vehicles, 4-wheeled vehicles, Bicycles, Cars, Bus,
Motorcycles for my contrived OOP exercise but was not sure how to specify
this.

Also, what is the right way to refer to class variables and methods that are
common for all classes: for eg. count of objects of a particular class? I
thought that ClassName.classvariable would be the way to go but your class
notes refer to these are self.classvariable - I thought, class variables
should have no concept of "self". Can you please clarify?

My answers are below -

>
> ========================= Homework =============================
>
> 1. Write a better loop for that flashcard program so that it exits
> if the user types 'q', and prints out the number right or wrong.
> Hint: you'll probably have to change quiz_user so it returns something
> other than just True or False.
>

#! /usr/bin/python
import random

class Flashcard:
    correct = 0
    wrong = 0
    def __init__(self, q, a):
        self.question = q
        self.answer = a

    def checkresult(self, response):
        flag = True
        str1 = self.answer.strip().lower().split()
            str2 = response.strip().lower().split()
            if(len(str1) == len(str2)):
                for i in range(len(str1)):
                        if str1[i] != str2[i]:
                                flag = False
                                    break
            else:
                      flag = False
        return flag

    def printresult(self, response):
        if self.checkresult(response):
            print "That's right!"
            Flashcard.correct += 1
        else:
            print "Sorry, Wrong. The Answer is {0}.".format(self.answer)
            Flashcard.wrong += 1

    def printtotals(self):
        print "Total: %d, Correct: %d, Wrong: %d\n" %
(Flashcard.correct+Flashcard.wrong, Flashcard.correct, Flashcard.wrong)
    def quiz_verify(self):
        t = raw_input("{0}\n".format(self.question))
        if t != 'q':
            self.printresult(t)
        else:
            self.printtotals()
        return t

    def __repr__(self):
        print "Flashcard: question: %s, answer: %s" % (self.question,
self.answer)

cards = [
    Flashcard("What are the colors of the US flag?" , "Red white blue"),
    Flashcard("Who is the President of the United States?" , "Barack
Obama"),
    Flashcard("Who is the Vice President of the United States?" , "Joe
Biden"),
    Flashcard("Who wrote the Declaration of Independence?" , "Thomas
JEFFERSON"),
    Flashcard("Who was the first President of the United States?" , "GEorge
Washington"),
    ]

def getrandomsample():
    return random.choice(cards).quiz_verify()

print "====================================="
while True:
    t = getrandomsample()
    if (t == "q"):
        print "Exiting"
        break
print "====================================="


> 2. Write a Quiz class that creates flashcards and runs the loop to
> quiz the user.
>

#! /usr/bin/python
import random

class Flashcard:
    def __init__(self, q, a):
        self.question = q
        self.answer = a

    def checkresult(self, response):
        flag = True
        str1 = self.answer.strip().lower().split()
            str2 = response.strip().lower().split()
            if(len(str1) == len(str2)):
                for i in range(len(str1)):
                        if str1[i] != str2[i]:
                                flag = False
                                    break
            else:
                      flag = False
        return flag

    def quiz_verify(self):
        t = raw_input("{0}\n".format(self.question))
        return t, self.checkresult(t)

    def __repr__(self):
        return "Flashcard: question: %s, answer: %s\n" % (self.question,
self.answer)

class Quiz:
    line = "====================================="
    def __init__(self):
        self.flashcards = []
        self.correct = 0
        self.wrong = 0

    def __add__(self, q, a):
        self.flashcards.append(Flashcard(q, a))

    def printtotals(self):
        print "Total: %d, Correct: %d, Wrong: %d\n" %
(self.correct+self.wrong, self.correct, self.wrong)

    def updatecount(self, res):
        if res:
            print "That's right!"
            self.correct += 1
        else:
            print "Sorry, Wrong."
            self.wrong += 1

    def quiz(self):
        print self.line
        while True:
            (t, r) = random.choice(self.flashcards).quiz_verify()
            if t == 'q':
                self.printtotals()
                print self.line
                print "Exiting"
                break
            else:
                self.updatecount(r)

    def __repr__(self):
        str = "Quiz: no of flashcards: %d\n" % (len(self.flashcards))
        for i in range(len(self.flashcards)):
            str = "%s %s" % (str, self.flashcards[i])
        return str

quiz = Quiz()
quiz.__add__("What are the colors of the US flag?" , "Red white blue")
quiz.__add__("Who is the President of the United States?" , "Barack Obama"),
quiz.__add__("Who is the Vice President of the United States?" , "Joe
Biden"),
quiz.__add__("Who wrote the Declaration of Independence?" , "Thomas
JEFFERSON"),
quiz.__add__("Who was the first President of the United States?" , "GEorge
Washington"),
#print quiz

quiz.quiz()

3. (optional) Rewrite your random sentence generation program from
> lesson 5 so it's object oriented. Hint: you could make your list of
> nouns, verbs etc. could be class variables, like "line" in my example
> above.
>
import random
class sentence:
    article =    [ "a", "the", "an"]
    subject =     [ "clock", "sun", "John", "Jane", "baby"]
    intran_verb =     [ "ran", "waited", "glowed", "delayed" ]
    tran_verb =     [ "fixed", "played", "hit", "rang" ]
    obj =         [ "me", "song", "game", "ball", "drum", "bell" ]
    adjective =     ["beautiful", "stupid", "weak", "kind", "lively" ]

    sentence =     [
        "{0} {1}.".format(random.choice(subject),
random.choice(intran_verb)),
             "{0} {1} {2}.".format(random.choice(subject),
random.choice(tran_verb), random.choice(obj)),
             "{0} {1} {2} {3}.".format(random.choice(subject),
random.choice(tran_verb), random.choice(adjective),
         random.choice(obj)),
        "{0} {1} {2}.".format(random.choice(article),
random.choice(subject), random.choice(intran_verb)),
             "{0} {1} {2} {3} {4}.".format(random.choice(article),
random.choice(subject), random.choice(tran_verb),
        random.choice(article), random.choice(obj)),
             "{0} {1} {2} {3} {4} {5}.".format(random.choice(article),
random.choice(subject),
        random.choice(tran_verb), random.choice(article),
random.choice(adjective), random.choice(obj)),
           ]

    def makesentence(self):
        return random.choice(self.sentence)

s = sentence()
while (True) :
    inp = raw_input("q to quit, enter to continue\n")
    if (inp == "q") :
        print "quiting"
        break
    else :
        print s.makesentence()



> 4. (optional) Come up with a better homework assignment for object-
> oriented programming in Python, then solve it. :-)
>
#! /usr/bin/python

# Create classes for authors and books and associate them with each other

class Author:
    def __init__(self, n, m, g):
        self.name = n
        self.email = m
        self.gender = g

    def getName(self):
        return self.name

    def setName(self, n):
        self.name = n

    def getEmail(self):
        return self.email

    def setEmail(self, m):
        self.email = m

    def getGender(self):
        return self.gender

    def setGender(self, g):
        self.gender = g

    def __repr__(self):
        return "Author: %s\t%s\t%s" % (self.name, self.email, self.gender)

class Book:
    def __init__(self, n, a, p, q):
        self.name = n
        self.author = a
        self.price = p
        self.qtyinstock = q

    def getName(self):
        return self.name

    def getAuthor(self):
        return self.author

    def getPrice(self):
        return self.price

    def setPrice(self, p):
        self.price = p

    def getQtyInStock(self):
        return self.qtyinstock

    def setQtyInStock(self, q):
        self.qtyinstock = q

    def __repr__(self):
        return "Book: %s\t[[%s]]\t%f\t%d" % (self.name, self.author,
self.price, self.qtyinstock)

def testAuthor():
    auth = Author("Jane Austen", "N/A", 'F')
    print auth
    auth.setEmail("jane.austen at ukpub.com")
    print auth
    return auth

def testBook():
    author = testAuthor()
    book = Book("Pride and Prejudice", author, 9.95, 1000)
    print book
    book1 = Book("Wuthering Heights", Author("Charlotte Bronte", "
charlotte.bronte at ukpub.com", 'F'), 9.95, 1000)
    print book1

testBook()



Thanks,
Prana


More information about the Courses mailing list