CONSTRUCT - Python's way of Ruby's "alias_method"

Ilias Lazaridis ilias at lazaridis.com
Fri Jun 9 20:49:15 CEST 2006


Slawomir Nowaczyk wrote:
> On Thu, 08 Jun 2006 15:28:39 +0300
> Ilias Lazaridis <ilias at lazaridis.com> wrote:
> 
> #> *IMPORT*
> #> 
> #> I would like to know, if this construct is valid, or if it can
> #> result in problems (that I do not see as a newcomer):
> 
> The intricacies of import are far beyond me, but FWIW I do not see
> anything wrong in this code.
> 
> #> Is there any way (beside a patch) to alter the behaviour to an
> #> existing function.
> 
> You can just assign new function to the old name. There are a few
> loops to hop through if you want to alter the behaviour of an existing
> *method*... There is an example -- I do not know if a good one -- here:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52192

This looks intresting, especially the comment, although I do not 
understand what is meant by "creates a cycle in the object".

"
There is a Better Way to Add Methods To Classes, Moshe Zadka, 2001/03/15
This method creates a cycle in the object for no reason at all. The 
following function will add any function to an instance in a cycle free way:

def add_method(self, method, name=None):
   if name is None: name = method.func_name
   class new(self.__class__): pass
   setattr(new, name, method)
   self.__class__ = new

Use as follows:

def pretty_str(self): pass

add_method(C(), pretty_str, '__str__')
"

-- 
http://lazaridis.com



More information about the Python-list mailing list