[Tutor] Class methods

Marc Tompkins marc.tompkins at gmail.com
Mon Jun 27 05:29:16 CEST 2011


On Sun, Jun 26, 2011 at 7:12 PM, David Merrick <merrickdav at gmail.com> wrote:

> Is it possible too have
>
> crit1 = Critter("Dave")
> crit2 = Critter("Sweetie")
> farm = [crit1,crit2]  #List#
>
> and then be able to use Critters methods on farm?
>
> No.  farm is a list, and lists don't inherit the methods of the objects
inside them (imagine what a nightmare _that_ would be, especially since
lists can contain more than one type of object at any given time!)

Instead, you would refer to the members of the list:
    farm[0].talk()
    farm[1].talk()
etc.  Only you wouldn't generally hard-code those numbers; instead, you
could use the "for x in y" style:
    for monster in farm:
        monster.talk()
At this point, "monster" is one of your Critters.  When I need a looping
variable for a collection of custom objects, I like to use words that are
synonymous with, or at least related to, the name of my custom class.  It
helps me keep track of what's going on - if I use x and y all over the
place, I tend to get confused.

You could also use a more traditional, less-Pythonic approach:
    for x in len(farm):
        farm[x].talk()
But seriously, why would you want to use Python to imitate Visual Basic?

By the way, you shouldn't ever need to refer to Dave and Sweetie by their
hard-coded variable names, so instead of instead of creating "crit1, crit2",
why not simply create them as members of the list?
    farm = []
    for critter_name in ["Dave", "Sweetie"]:
        farm.append(Critter(critter_name))
Now the variables don't have names per se, but you can still refer to them
by number if you need one in particular, or you can just loop over the list
with "for monster in farm".

Finally, maybe a dictionary would be more useful/intuitive than a list?
    farm = []
    for critter_name in ["Dave", "Sweetie"]:
        farm[critter_name] = Critter(critter_name)
    farm["Dave"].talk()

I do think that "farm" is going to be a little misleading as a name for a
collection of Critters; might I suggest "herd" or "swarm"?  Just a
thought...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110626/a3b8df7e/attachment.html>


More information about the Tutor mailing list