[Tutor] __init__ for class instantiation?

antonmuhin at rambler.ru antonmuhin at rambler.ru" <antonmuhin@rambler.ru
Fri Apr 25 12:19:00 2003

Hello Zak,

Friday, April 25, 2003, 7:51:51 PM, you wrote:

ZA> Here's a short history: I'm working on an interactive fiction engine, and
ZA> I'd like to create a list of verbs dynamically, based on the classes
ZA> created.

ZA> My current solution is to define the class, then run a verb-grabber
ZA> function right after that definition:

ZA> import wordlist

ZA> def getActions (thingClass):
ZA>     for m in dir (thingClass):
ZA>         if m [:4] == 'act_':
ZA>             wordlist.addVerb (m [4:])

ZA> # Player class, where act_* defines a verb
ZA> class Player (Thing):
ZA>   def __init__ (self):
ZA>      ... code ...
ZA>   def act_go (self, parsed):
ZA>      ... code ...
ZA>   def act_look (self, parsed):
ZA>      ... code ...

ZA> getActions (Player)

ZA> ---

ZA> My question is: Is there a function I can define in the base Thing class
ZA> which would run once Player (or any other Thing child) has been fully
ZA> defined? Or is my current solution as close as I can get?

ZA> ---

ZA> Lastly, thanks for the quick answers to my last question! I'm looking
ZA> forward to being a contributing part of this list.

I hope that this example might be of interest for you:

class MetaVerbPrinter(type):
    def __new__(cls, name, bases, dict):    
        print "Verbs of class", name, ">", [m for m in dict if m.startswith("act_")]
        return type.__new__(cls, name, bases, dict)
class Thing:
    __metaclass__ = MetaVerbPrinter
class Player (Thing):
    def __init__ (self): pass
    def act_go (self, parsed): pass
    def act_look (self, parsed): pass

*Warning* I'm just playing with metaclasses and I'm not an expert.

Best regards,
 anton                            mailto:antonmuhin@rambler.ru