OOP: How to implement listing al 'Employees'.

Mike Orr sluggoster at gmail.com
Mon Dec 31 15:53:06 EST 2007


On Dec 29, 1:53 am, Petar <peros... at gmail.com> wrote:

> Let me explain how I got to this question. I had written een Article
> class which handled the articles that I had. On a certain page I
> wanted to show all the articles. That got me wondering about what to
> do. Should I make a method in my Article.class which returned multiple
> articles, or should I just use my current Article.class and fill a
> list (with a loop) with articles. The first solution thus meaning
> writing another method, the latter method to just use the current
> Article.class and call it multiple times.

A class method would be ideal for this if you have no other reason to
create an Articles class:

    @classmethod
    def all(class_):
        ret = []
        for a in THE_ARTICLES:
            article = class_(a)
            ret.append(article)
        return ret

Definitely don't use an instance method, which is expected to operate
on one article without making additional Article instances.

Mark 'Blackjack' Rintsch wrote:
> Then maybe it should not be a class.  Maybe a function returning
> `Article`\s would be enough.  This is not Java, not everything
> has to be stuffed into classes.

True, but this function is logically related to the Article class, so
it's convenient to put them together.  Then the user can just "from __
import Article" rather than "from __ import Article, get_all_articles,
what_was_that_other_function?".



More information about the Python-list mailing list