Nick Keighley wrote:
Hi,
I'm a Python beginner and I'm would like to write a function that
returns a class (perhaps a tad ambitious...). I've looked through
the FAQ and perused "Python In A Nutshell" (not a good book to
start with?). The only example I found in PiaN used a simple
Hi,
I'm a Python beginner and I'm would like to write a function that
returns a class (perhaps a tad ambitious...). I've looked through
the FAQ and perused "Python In A Nutshell" (not a good book to
start with?). The only example I found in PiaN used a simple
the Nutshell should be helpful -- if you're a newbie to programming,
you should start with easier books (but with the kind of tasks
you're setting yourself I guess you aren't). I didn't particularly
emphasize metaprogramming in the Nutshell -- it's more of a "gee
whiz" kind of thing and the Nutshell aims to cover solid, everyday,
bread-and-butter usage.
if statement to return one of a selection of pre-existing classes.
I'd like to generate a class on-the-fly from a parameter (a dictionary).
How do you want to use that dict -- as the class's dict? Then either:I'd like to generate a class on-the-fly from a parameter (a dictionary).
def makeaclass(fromdict):
class X: pass
X.__dict__ = fromdict
return X
or
def makeaclass(fromdict):
class X: pass
X.__dict__.update(fromdict)
return X
might be helpful.
Can Python do this sort of stuff? Does the mean I have to mess with
the dreaded meta-classes?
Metaclasses may be easier to use than sufficiently-general class-buildingthe dreaded meta-classes?
functions, actually -- no reason to dread them. But anyway, yes, Python
IS pretty good at metaprogramming, too, both with and without metaclasses.
Alex