Mangle function name with decorator?

andrew cooke andrew at acooke.org
Tue Mar 17 12:52:22 EDT 2009


Adam wrote:
> class A(object):
>     def __init__(self, method, usebar = False):
>         self.method = method
>         self.usebar = usebar
>
>     def __call__(self):
>         if self.usebar == True:
>             mangled_name = "_bar_" + self.method
>             if hasattr(self, mangled_name):
>                 return getattr(self, mangled_name)()
>             else:
>                 return getattr(self, self.method)()
>         else:
>             if hasattr(self, self.method):
>                 return getattr(self, self.method)()
>             else:
>                 raise NotImplementedError
>
>     @bar
>     def foo(self):
>         print "in _bar_foo"
>
>     def foo(self):
>         print "in foo"


this isn't exactly what you ask for, but it gives a similar result.  it's
kind of obvious, but it's possible you didn't know methods were first
class entities.

class Foo:

  def __init__(self, useBar=False):
    if useBar:
      self.foo = self.__bar
    else:
      self.foo = self.__foo

  def __foo(self):
    print('foo')

  def __bar(self):
    print('bar')

andrew




More information about the Python-list mailing list