Bulk Adding Methods Pythonically

Rob Gaddi rgaddi at highlandtechnology.invalid
Wed Jun 15 14:39:08 EDT 2016


Random832 wrote:

> On Wed, Jun 15, 2016, at 13:37, Rob Gaddi wrote:
>> I've got a whole lot of methods I want to add to my Channel class, all
>> of which following nearly the same form.  The below code works, but
>> having to do the for loop outside of the main class definition feels
>> kludgey.  Am I missing some cleaner answer?
>
> Inside the class definition you can add things to locals() [it returns
> the actual dictionary being used in class preparation], but I don't know
> if this can be relied on or is an implementation detail of CPython.
> Anyone know?
>
> But anyway, instead of using a loop, why not just define each one on its
> own line:
>
> def mkmeasure(fnname, measparam):
>    ...
>
> class Channel:
>    frequency = mkmeasure('frequency', 'FREQ')
>    falltime = mkmeasure('falltime', 'FTIM')

Thought about it, but whenever I'm dropping 20-someodd of those there's
inevitably some place where I screw up the replication of the quoted
name and the bound name.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.



More information about the Python-list mailing list