[Tutor] Clash of the Titans and Mundane Matters
Sean Perry
shaleh at speakeasy.net
Thu Jan 20 09:23:46 CET 2005
Michael Powe wrote:
> Clash of the Titans
>
snip constructor discussions
Pilgrim is pedantically correct but Alan's comment matches how most of
us think about it.
>
> ----------------
> Mundane Matters
>
> I'm having a hard time with classes in python, but it's coming
> slowly. One thing that I think is generally difficult is to parse a
> task into "objects." 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.
while that is a valid approach, it is not how most of us would do it. By
subclassing you have to edit the code every time a new expense type is
added. Ever used MS Money or Quicken? Imagine if the type of each item
was a subclass. Use a string.
>
> A similar problem occurs with my HTML-parsing routine that I brought
> to the list recently. Use of HTMLParser was suggested. I've looked
> into this and usage means subclassing HTMLParser in order to implement
> the methods in the way that will accomplish my task. Conceptually,
> I'm having a hard time with the "object" here. (The fairly poor
> documentation for HTMLParser doesn't help.) Apparently, I'm creating
> a "parser" object and feeding it data. At least, that's the closest I
> can get to understanding this process. How I'm actually feeding data
> to the "parser" object and retrieving the results are matters open to
> discussion. I'll be working on that when I get another chance.
>
This counts the tags in a html file piped in on stdin.
#!/usr/bin/python
import sys, HTMLParser
class TagCounter(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.tags = {}
def handle_starttag(self, tag, attrs):
self.tags[tag] = self.tags.setdefault(tag, 0) + 1
if __name__ == '__main__':
counter = TagCounter()
for line in sys.stdin.xreadlines():
counter.feed(line)
counter.close()
print counter.tags
> Finally, in terms of "understanding python," the question I keep
> coming up against is: why do we have both functions and methods?
> What is the rationale for making join() a string method and a os.path
> function?
>
a method is a function bound to a class. Nothing super special.
More information about the Tutor
mailing list