[Tutor] Object Orientation : Class XXX : def __init__

Max Noel maxnoel_fr at yahoo.fr
Thu Nov 4 19:02:45 CET 2004


On Nov 4, 2004, at 17:40, kumar s wrote:

> def __init__ function.
>
> Could any one help me please defining __init__
> function in terms of a python program.

	The __init__ method of a class is called every time you instantiate 
the class, i.e. each time you use the class to create a new object.
	Attached to this message is a fairly simple class I made: a Dice 
class, used to roll dice (duh). It's a little bit more complex than 
what a "basic" Dice class would be because I'm a roleplayer and thus 
need dice that are not necessarily six-sided and can be open-ended 
(i.e. if you roll the max result, reroll the dice and add); however it 
shouldn't be hard to understand.
	The __init__ function, here, is called each time you use the class to 
create a new die. It is used to set the die's characteristics: number 
of sides, and open-endedness. In the following piece of code:


#!/usr/bin/env python

import Dice

sixSider = Dice.Dice()
twentySider = Dice.Dice(numSides=20, openEnded=False)
closeEndedSixSider = Dice.Dice(numSides=6, openEnded=False)



	Three dice are created. The parameters used in creating the class are 
passed to the __init__ method (in my example, parameters are not needed 
as defaults are provided).
	Therefore, sixSider is a standard, 6-sided, open-ended die (yeah, 
being a Shadowrun player, I use open-ended as a default). twentySider 
is a close-ended D20 (for D&D players). closeEndedSixSider is a 
close-ended D6.
	Now that they have been created, you can do whatever you want with 
them: roll them (for example, sixSider.roll() ), alter them (if you 
decide that after all you want your D20 to be open-ended, use 
twentySider.setOpenEnded(True) ), etc.

	You may also want to have a look at the OOP part of Guido's tutorial 
on www.python.org ; and of course you're welcome to keep asking 
questions here.

HTH,

-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"
-------------- next part --------------
Skipped content of type multipart/appledouble


More information about the Tutor mailing list