Create a class at run-time

Michiel Overtoom motoom at xs4all.nl
Thu Mar 25 18:18:17 EDT 2010


On 2010-03-25 23:00, Michel wrote:

> I'm trying to dynamically create a class. What I need is to define a
> class, add methods to it and later instantiate this class. Methods
> need to be bound to the instance though, and that's my problem.

Maybe this snippet is of any help?

import functools

class Template(object):
     pass

def printmyname(self):
     print self.name

t=Template()
t.name="Pete"
t.printmyname=functools.partial(printmyname,t)

u=Template()
u.name="Mary"
u.printmyname=functools.partial(printmyname,u)

t.printmyname()
u.printmyname()

Greetings,


-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Valloppillil
http://www.catb.org/~esr/halloween/halloween4.html



More information about the Python-list mailing list