Perl vs. Python question...
Joshua Judson Rosen
rozzin at geekspace.com
Sun Jul 12 08:57:03 EDT 2009
Paul Lussier <p.lussier at comcast.net> writes:
>
> Hi Folks,
>
> How do I create dynamically created methods in python classes?
>
> For example, if I have a number of member variables which I want to get
> or set, I don't want to have to create getters and setters for each
> attribute, since the code would largely be the same, just the variable
> I'm dealing with would be different.
Rather than implementing a whole bunch of similar `get_*()' and
`set_*()' methods in Python, you can just define __getattr__() and
__setattr__():
http://docs.python.org/reference/datamodel.html#object.__getattr__
How's that? Perfect fit? :)
Alternately (e.g.: something other than `getters and setters'): can't
you just create a single method that takes an `extra' parameter?
Even if you really do really want to `lots of methods' interface, I'd
still start with unified dispatcher-method--then the other methods
would just be simple wrappers, e.g.:
class C:
def do_stuff(self, key, *args):
print 'doing %s stuff...' % key
do_x = lambda self, *args: self.do_stuff('x', *args)
do_y = lambda self, *args: self.do_stuff('y', *args)
do_z = lambda self, *args: self.do_stuff('z', *args)
You could even set all of those `C.do_*' attributes (which become
methods) automatically, e.g.:
for key in ('xray', 'yankee', 'zulu'):
def do_predispatched_stuff_stuff(self, *args):
return self.do_stuff(key, *rags)
setattr(C, key, do_predispatched_stuff)
--
Don't be afraid to ask (Lf.((Lx.xx) (Lr.f(rr)))).
More information about the gnhlug-discuss
mailing list