Binding first parameter of method to constant value

DPalao dpalao.python at gmail.com
Fri May 18 09:04:12 EDT 2012


On Viernes mayo 18 2012 14:14:33 Johannes Bauer escribió:
> Hi group,
> 
> I'm trying to dynamically add methods to a class at runtime. What I
> would like to do is have them all delegated to one common function which
> is called with the name of the function as first parameter. I.e.:
> 
> class Foo():
>   def __init__(self):
>     # Some magic missing here
>     setattr(self, "foometh", types.MethodType(self._dispatcher, self))
>     setattr(self, "barmeth", types.MethodType(self._dispatcher, self))
> 
>   def _dispatcher(self, caller, *args):
>     # Dispatcher called with caller == "foometh"
>     # or caller == "barmeth", depending on which one was called
> 
> 
> with the effect that
> 
> f = Foo()
> f.foometh(1, 2, 3)
> # -> this should be equivaent to  Foo._dispatcher(f, "foometh", 1, 2, 3)
> 
> f.barmeth()
> # -> this should be equivaent to  Foo._dispatcher(f, "barmeth")
> 
> I'm kind of stuck. Can you please give me hints?
> 
> Best regards,
> Joe
> 
> >> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> > 
> > Zumindest nicht öffentlich!
> 
> Ah, der neueste und bis heute genialste Streich unsere großen
> Kosmologen: Die Geheim-Vorhersage.
>  - Karl Kaos über Rüdiger Thomas in dsa <hidbv3$om2$1 at speranza.aioe.org>

Hi Johannes,
If I understood well your question, for specific attributes I recommend you to 
have a look at properties and descriptors (I love them).
For a general way to deal with attributes: the __getattr__ (to handle 
undefined attributes), __getattribute__ (to handle *every* attribute; be 
careful with loops), and __setattr__ (to catch *every* attribute assignmet, 
same warning concerning loops).

Hope it helps.
BR,

DPalao




More information about the Python-list mailing list