Create a class at run-time

Michel michel.metzger at gmail.com
Fri Mar 26 16:00:57 CET 2010


Well, I don't have the reference to the instance. The class is
actually instantiated later by a the unittest library.

On Mar 25, 6:18 pm, Michiel Overtoom <mot... at xs4all.nl> wrote:
> 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 Valloppillilhttp://www.catb.org/~esr/halloween/halloween4.html




More information about the Python-list mailing list