[Tutor] __init__ for class instantiation?

Dana Larose dana@pixelenvy.ca
Fri Apr 25 12:21:16 2003


On Fri, 25 Apr 2003, Zak Arntson wrote:

> Here's a short history: I'm working on an interactive fiction engine, and
> I'd like to create a list of verbs dynamically, based on the classes
> created.
>
> My current solution is to define the class, then run a verb-grabber
> function right after that definition:
>
> import wordlist
>
> def getActions (thingClass):
>     for m in dir (thingClass):
>         if m [:4] == 'act_':
>             wordlist.addVerb (m [4:])
>
> # Player class, where act_* defines a verb
> class Player (Thing):
>   def __init__ (self):
>      ... code ...
>   def act_go (self, parsed):
>      ... code ...
>   def act_look (self, parsed):
>      ... code ...
>
> getActions (Player)
>
> ---
>
> My question is: Is there a function I can define in the base Thing class
> which would run once Player (or any other Thing child) has been fully
> defined? Or is my current solution as close as I can get?
>

If I understand what you want to do, why not put getActions in the
__init__ method of Thing?  Then, at the end of __init__ for Player (or
other child classes you define), call Thing's constructor:

class Thing:
     def __init(self):
          ... code ....
          self.getActions()

class Player(Thing):
     def __init__(self):
         ... code ...
         Thing.__init__(self)

dana.