[Tutor] Re: Help with classes

Andrei project5 at redrival.net
Fri Apr 8 14:27:46 CEST 2005


Kevin <python.programming <at> gmail.com> writes:

> Well this OOP stuff is realy hard for me as I have never even
> programmed it took me a while just to understand defs. However I am
> determined to learn how to do it. My biggest problem is with __init__
> I still don't understand how to use it. Though I did try somthing
> different with my code rather then having the dict of commands in the
> main part of the code, I put it in th __init__ of class Comands like
> so:

__init__ is called when a new instance of that class (an object) is created.
It's particularly useful when used with certain arguments in order to initialize
certain properties of an object. Let's say you have a number of enemies and each
enemy has a certain name and strength. You can then define a class like this:

class Enemy:
    def __init__(self, name, strength):
        self.name = name
        self.strength

and create any number of enemies like this:

enemy1 = Enemy('Gargoyle', 10) # calls __init__
enemy2 = Enemy('Soldier', 3)

If you then ask enemy1 about its name, it wall answer:

>>> print enemy1.name
'Gargoyle'

> When a player type is "get sword" it will add a sword to there
> inventory. Wich I'm not sure if I am going about this the right way.

That part about the sword in the inventory sounds right. Let's do a quick dummy
implementation:

class Player:
    def __init__(self, name, strength):
        self.name = name
        self.inventory = [] # player always starts with empty inventory
        self.strength = strength
    def PickUp(self, item):
        # the player can only cary the amount of stuff around
        # that is allowed by his strength
        if len(self.inventory)==self.strength:
            print "You are not strong enough to pick that up!"
        else:
            self.inventory.append(item)
            print "You've picked up a %s" % item.name

class Item:
    def __init__(self, name):
        self.name = name

conan = Player('Conan the Barbarian', 3)
excalibur = Item('sword')
bottle = Item('bottle of water')
ball = Item('crystal ball')
scroll = Item('ancient scroll')

conan.PickUp(excalibur)
conan.PickUp(ball)
conan.PickUp(scroll)
conan.PickUp(bottle) # will fail

donan = Player('Donan the Civilized', 2) # different player!
donan.PickUp(bottle) # can pick it up, because donan != conan



(The implementation above has some obvious problems, like not being able to drop
anything, a sword demanding just as much strength as a bottle and most
importantly the fact that donan will be able to pick up excalibur even though
conan already has it.) 
You can see that conan and donan are both players (Player objects), but each of
them has his own name, inventory and strength. Even if conan's inventory is
full, donan can still pick up new things.

Yours,

Andrei



More information about the Tutor mailing list