1

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
  • 2
    What is a "dynamic subclass" exactly? Does get_class() return one of several predetermined classes, or an instance of one, or does it actually create entirely new types? Commented Jan 5, 2015 at 4:40
  • 1
    I hope this is just a simple example to explain your question, because creating a bunch of classes merely to accommodate a variable number of attributes named like that does not look like a good design: it would be better to make a single class that stores those attributes in a tuple or list. Commented Jan 5, 2015 at 5:22

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.