Making helper methods more concise

Arnaud Delobelle arnodel at gmail.com
Mon Apr 16 08:36:41 EDT 2012


On 16 April 2012 13:29, Arnaud Delobelle <arnodel at gmail.com> wrote:
> You can do this (untested), but no doubt it won't be to everybody's taste:
>
> class A(object):
>   def __init__(self):
>       self.listing = []
>
>   # This method does the work.
>   def append_text(self, text, style):
>       self.listing.append((text, style))
>
>   # The rest of the methods are just helpers.
>   for style in 'paragraph', 'header', 'title':
>       exec """def append_%s(self, text):
>           self.append_text(text, "%s")""" % (style, style.capitalize())
>   del style

Oops I sent too quickly.  Another way would be

class A(object):
  def __init__(self):
      self.listing = []

  # This method does the work.
  def append_text(self, text, style):
      self.listing.append((text, style))

for style in 'paragraph', 'header', 'title':
   setattr(A, 'append_' + style, lambda s, t, style=style:
A.append_text(s, t, style))

Untested too :)

Cheers,

Arnaud



More information about the Python-list mailing list