ClassExample3.py

From dftwiki3
Jump to: navigation, search

--D. Thiebaut 02:43, 26 January 2010 (UTC)

Exercise
Create a new version of ClassExample1.py such that we create a 3rd document which is the concatenation of the other two. It is not acceptable to create docuClass( text1 + text2 )! (although it would be a good solution otherwise). Assume that you cannot modify the class docuClass in any way. Use operator overloading if you can!
#! /usr/bin/python
# D. Thiebaut
# Version 2, based on classExample.py
# Solution 1 to exercise:
# create a 3rd object that is the concatenation of the first two.
#

class docuClass:
    def __init__( self, doc ):
        self.doc = doc
        self.lines = doc.split( "\n" )
        self.wordCount = len( doc.split() )

    def getWordCount( self ):
        return self.wordCount

    def getLines( self ):
        return self.lines

    def display( self ):
        for line in self.lines:
            print line
                
class docuPlusClass( docuClass ):
    def __init__( self, doc ):
        docuClass.__init__( self, doc )

    def __add__( self, newDoc ):
        return docuPlusClass (
               '\n'.join( self.lines + newDoc.getLines() ) )
    

def main():
    doc1 = docuPlusClass( """`Have some wine,' the March Hare said in an encouraging tone.
Alice looked all round the table, but there was nothing on it but tea.
`I don't see any wine,' she remarked.
`There isn't any,' said the March Hare.
`Then it wasn't very civil of you to offer it,' said Alice angrily.
`It wasn't very civil of you to sit down without being invited,'
said the March Hare. """ )
    doc2 = docuPlusClass( """Piglet sidled up to Pooh from behind. "Pooh," he whispered.
"Yes, Piglet?"
"Nothing," said Piglet, taking Pooh's paw,
"I just wanted to be sure of you."
""" )
    
    print "doc1"
    doc1.display()

    print "doc2"
    doc2.display()

    doc3 = doc1 + doc2

    print "doc3"
    doc3.display()

    
main()