how to dynamically create class methods ?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Mar 27 04:16:31 EDT 2008


On Wed, 26 Mar 2008 00:55:22 -0700, Arnaud Delobelle wrote:


[snip]
> Except it only *appears* to work.  What happens if were store the
> instances in a list and then execute them all in one go?

Ah yes, nicely spotted. Another solution would be to use a proper factory 
function:

def factory(record):
    def f(n):
        return (record + " ")*n
    return f

class MyClass(object):
    pass

records = ["spam", "ham"]
instances = []
for record in records:
    instance = MyClass()
    setattr(instance, 'execute', factory(record))
    instances.append(instance)

for instance in instances:
    instance.execute(5)


-- 
Steven



More information about the Python-list mailing list