Pythonic way to add method alias in subclass

Carl Banks pavlovevidence at gmail.com
Sat Dec 15 09:22:42 EST 2007


On Dec 15, 8:03 am, Lee Harr <miss... at frontiernet.net> wrote:
> I thought of several ways to add another name for
> a method in a subclass ...
>
> #alias.py
> class Foo(object):
>     def nod(self):
>         print "nodding"
>
> class Bar(Foo):
>     def __init__(self):
>         self.agree = self.nod
>
> class Bar2(Foo):
>     agree = Foo.nod
>
> class Bar3(Foo):
>     def agree(self):
>         Foo.nod(self)
>
> def alias(method):
>     def dec(m):
>         return method
>     return dec
>
> class Bar4(Foo):
>     @alias(Foo.nod)
>     def agree(self):
>         pass
>
> b = Bar()
> b.agree()
>
> b2 = Bar2()
> b2.agree()
>
> b3 = Bar3()
> b3.agree()
>
> b4 = Bar4()
> b4.agree()
> #####################
>
> I am leaning towards Bar2 since it has the least code.
> Any thoughts?

1, 2, and 3 are all fine.  1 would be useful if for some reason you
wanted to change the behavior of Bar.agree at runtime.  3 has a few
minor advantages: stack traces will print "agree" instead of "nod", it
could be easier to modify later, slightly more self-documenting.  And
if you had been using super(), you could have avoided repeating the
symbol Foo.  But 2 is more efficient and less typing than 3.

Option 4 is abhorrent.


Carl Banks



More information about the Python-list mailing list