how to repeat function definitions less
Michele Simionato
michele.simionato at gmail.com
Sun Mar 15 02:05:19 EDT 2009
On Mar 15, 12:09 am, s... at pobox.com 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)
> ...
The first thing coming to my mind is a class decorator:
def addcolors(*colors):
def dec(cls):
for color in colors:
def col(self, value, color=color, level='INFO'):
self.write(value, color, level)
col.__name__ = color
setattr(cls, color, col)
return cls
return dec
@addcolors('red', 'gold')
class C(object):
def write(self, value, color, level):
pass
More information about the Python-list
mailing list