Pythonic way to add method alias in subclass

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sat Dec 15 08:54:48 EST 2007


Lee Harr a écrit :
> 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

Will create an instance attribute of type method for each instance of 
Bar. Which might or not be a problem FWIW.

> class Bar2(Foo):
>     agree = Foo.nod

The One Obvious Way.

> class Bar3(Foo):
>     def agree(self):
>         Foo.nod(self)

Are you willing to take the penalty of an extra method call ?

> def alias(method):
>     def dec(m):
>         return method
>     return dec
> 
> class Bar4(Foo):
>     @alias(Foo.nod)
>     def agree(self):
>         pass
> 

Bad case of arbitrary overcomplification IMHO. Nothing with metaclasses 
while we're at it ?-)

(snip)

> I am leaning towards Bar2 since it has the least code.

Indeed.

> Any thoughts?

cf above.



More information about the Python-list mailing list