how to repeat function definitions less

MRAB google at mrabarnett.plus.com
Sun Mar 15 00:54:58 CET 2009


alex goretoy wrote:
> I'm doing this in my code, how to make it define all this functions for 
> me with lambda, I've been up for a while and cant seem to figure it out, 
> whats the most efficient way to do it? with lambda? how? thx
> 
>     def red(self,value,color='red',level='INFO'):
>         self.write(value,color,level)
>     def gold(self,value,color='gold',level='INFO'):
>         self.write(value,color,level)
>     def green(self,value,color='green',level='INFO'):
>         self.write(value,color,level)
>     def blue(self,value,color='blue',level='INFO'):
>         self.write(value,color,level)
>     def yellow(self,value,color='yellow',level='INFO'):
>         self.write(value,color,level)
>     def purple(self,value,color='purple',level='INFO'):
>         self.write(value,color,level)
>     def w_red(self,value,color='white_on_red',level='INFO'):
>         self.write(value,color,level)
>     def w_gold(self,value,color='white_on_gold',level='INFO'):
>         self.write(value,color,level)
>     def w(self,value,color="red",level="INFO"):
>         self.write(value,color,level)
>     def write(self,value,color="red",level="INFO"):
>         """
>         write - output message,take value string or list,color=""
>         """
>         self._hero(value,color,level)
> 
How about this:

method_info = """\
red
gold
green
blue
yellow
purple
w_red white_on_red
w_gold white_on_gold
w red
"""

class MyClass(object):
     def write(self, value, color="red", level="INFO"):
         print "value=%s, color=%s, level=%s" % (repr(value), 
repr(color), repr(level))

for line in method_info.splitlines():
     parts = line.split()
     func_name, color_name = parts[0], parts[-1]

     def func(self, value, color=color_name, level='INFO'):
         MyClass.write(self, value, color, level)

     setattr(MyClass, func_name, func)

m = MyClass()
m.red("red_value")




More information about the Python-list mailing list