[Tutor] Populating a list with object to be called by a class

eryksun eryksun at gmail.com
Thu Sep 20 18:25:35 CEST 2012

On Thu, Sep 20, 2012 at 10:41 AM, Ara Kooser <ghashsnaga at gmail.com> wrote:
> I have a list that tracks the ants but I did this is a very crude way. I
> basically copied and pasted everything in there like this:
> ants =
> [Ant("Red_1","Red","yellow_food"),Ant("Yellow_1","Yellow","red_food"),
> Ant("Red_2","Red","yellow_food"),Ant("Yellow_2","Yellow","red_food"),

Having the type as instance data is limiting. Consider creating the
subclasses RedAnt and YellowAnt, instead. For example, "red_food" can
be a default argument for YellowAnt. You can also use a class counter
variable that gets incremented for each new ant. Then the names can be
automatic, too, but with the option to use a specific name.

    class Ant(object):
        _count = 0

        def __init__(self, name=None, food='food'):
            cls = self.__class__
            if cls == Ant:
                raise NotImplementedError

            cls._count += 1
            if name is None:
                self.name = "%s_%s" % (cls.__name__, cls._count)
                self.name = name
            self.food = food

        def __repr__(self):
            clsname = self.__class__.__name__
            name = repr(self.name)
            food = repr(self.food)
            return "%s(%s, %s)" % (clsname, name, food)

        def __str__(self):
            return str(self.name)

    class RedAnt(Ant):

        def __init__(self, name=None, food="yellow_food"):
            super(RedAnt, self).__init__(name, food)

    class YellowAnt(Ant):

        def __init__(self, name=None, food="red_food"):
            super(YellowAnt, self).__init__(name, food)

For example:

    >>> ants = [cls() for i in range(2) for cls in (RedAnt, YellowAnt)]
    >>> ants
    [RedAnt('RedAnt_1', 'yellow_food'), YellowAnt('YellowAnt_1', 'red_food'),
     RedAnt('RedAnt_2', 'yellow_food'), YellowAnt('YellowAnt_2', 'red_food')]

    >>> print ', '.join(str(a) for a in ants)
    RedAnt_1, YellowAnt_1, RedAnt_2, YellowAnt_2

    >>> Ant()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 8, in __init__

    >>> RedAnt('Tom', 'mice')
    RedAnt('Tom', 'mice')

    >>> YellowAnt('Jerry', 'cheese')
    YellowAnt('Jerry', 'cheese')

    >>> RedAnt._count, YellowAnt._count, Ant._count
    (3, 3, 0)

More information about the Tutor mailing list