method = Klass.othermethod considered PITA

Erik Max Francis max at alcyone.com
Sat Jun 4 20:55:51 EDT 2005


Steven Bethard wrote:

> John J. Lee wrote:
>
>> It seems nice to do this
>> 
>> class Klass:
>> 
>>     def _makeLoudNoise(self, *blah):
>>         ...
>> 
>>     woof = _makeLoudNoise
> 
> Out of curiosity, why do you want to do this?

There aren't too many clear use cases, but I've found it useful from 
time to time.  Usually it comes in handy when you're specializing some 
predefined behavior, often when relying on introspection in some fashion.

For instance, for a chat network bot framework, a certain form of bot 
will look for any attribute in its instance that starts with verb_ and a 
command and execute it when it hears it spoken:

	def verb_hello(self, convo):
	    "Respond to a greeting."
	    convo.respond(random.choice(self.greetings))

If you'd like it to respond to more than one word like this, then you 
only need to assign the additional verbs, rather than redefine them:

	verb_hi = verb_hello
	verb_yo = verb_hello
	verb_wazzup = verb_hello

It actually does more than this, where a builtin help system (verb_help) 
which relies on the docstrings of the verb_... methods will allow you to 
get help on any defined verb automatically, and list the known verbs 
when supplied without arguments.  But this would list duplicate verbs 
for the aliases (hi, yo, wazzup) above, which isn't optimal.  So instead 
I have another prefix, alias_, which acts as a verb, but won't be 
automatically scanned as a verb when help is finding the list of valid 
verbs:

	alias_hi = verb_hello
	...

That way, you get maximum effectiveness for minimum clutter.

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Things are as they are because they were as they were.
   -- Thomas Gold



More information about the Python-list mailing list