I want to write a function creating dynamic subclass. For example:
def get_class(num):
...
...
return _class
This function accepts an integer num and then constructs such a class
class Test(BaseClass):
attr_1 = 1
attr_2 = 1
...
attr_num = 1
and return it.
I wonder whether this is possible WITHOUT writing a metaclass.
2 Answers 2
As mentioned in the other answer, you can either use type, in which case you dynamically construct attributes:
def foo(num, **kwargs):
kwargs.update({'num': num})
return type('Foo', (BaseClass,), kwargs)
or if you dont need dynamic keys you can then simply manually instantiate a class:
def foo(num):
class Foo(BaseClass):
num = num
return Foo
Comments
You can use the type function to dynamically create a class. The documentation for type pretty much describes exactly what you're trying to accomplish. Something like this:
class BaseClass(object):
pass
def get_class(num):
attrs = [('attr_%d' % i, 1) for i in range(num)]
return type('Test', (BaseClass,), dict(attrs))
get_class()return one of several predetermined classes, or an instance of one, or does it actually create entirely new types?