Here's an example: in Java, I wrote an
application to track my travelling expenses (I'm a consultant; this
tracking of expenses is the itch I am constantly scratching. ;-)
I've also written this application in a perl/CGI web application as
well.) It's easy to see the outline of this task: create an abstract
class for expense and then extend it for the particular types of
expenses -- travel, food, transportation, lodging and so forth. In
python, I guess I'd create a class and then "subclass" it. But
... what are reading/writing to files and printing?
I'm not sure exactly what output you're after ... But what about something like this?
class Expense(object): def __init__(self, amount): self.amount = amount
class Travel(Expense): def __str__(self): return 'Travel: $%.2f' % float(self.amount)
class Food(Expense): def __str__(self): return 'Food: $%.2f' % float(self.amount)
class Accommodation(Expense): def __str__(self): return 'Accommodation: $%.2f' % float(self.amount)
myExpenses = [Travel(2300), Accommodation(200), Food(12.50), Food(19.95), Food(2.35), Travel(500)]
for e in myExpenses: print e
out = file('myExpenses.txt', 'w') for e in myExpenses: out.write(str(e) + '\n') out.close()
--------------------------------------------------------------------- This produces output:
Travel: $2300.00 Accommodation: $200.00 Food: $12.50 Food: $19.95 Food: $2.35 Travel: $500.00
and the same in the file 'myExpenses.txt'.
The str() function automatically calls .__str__() on its argument (if you don't define __str__, it will call a boring default one). And the print command automatically calls str() on its arguments.
-- John. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor