Creating new classes on the fly
Troy Melhase
troy.melhase at gmail.com
Tue Oct 5 17:04:39 EDT 2004
On Tue, 5 Oct 2004 17:53:35 -0300, Carlos Ribeiro <carribeiro at gmail.com> wrote:
> I need to create new classes on the fly with different default
> parameters, stored as class attributes. Of course, there's a reason
> behind it: I need new classes, because I need to be able to build
> multiple instances of them later. And I need new defaults, because the
> values can't be provided at instantiation time (because of scoping &
> mutability issues).
I've had the same need recently, and I've found that coding the class
as part of a closure is readable (untested code):
def my_custom_class():
some_param = lookup_param() # now part of the lexical scope, can be mutable
class MyCustomClass:
default_param = some_param
return MyCustomClass
CustomizedClass1 = my_custom_class()
CustomizedClass2 = my_custom_class()
instances_of_one = [CustomizedClass1(), CustomizedClass1(), ]
instances_of_two = [CustomizedClass2(), CustomizedClass2(), ]
Good luck,
troy
More information about the Python-list
mailing list