Dynamic creation of an object instance of a class by name

Jacek Generowicz jacek.generowicz at cern.ch
Thu Apr 8 04:41:45 EDT 2004


Andre Meyer <meyer at acm.org> writes:

> Right, ok, well, I do not assume to know what classes can be
> instantiated,

But you are assuming that you have a string which knows, right ...

> thus anything like accessing globals() is not likely to help,
> sorry. The eval() version works pretty ok so far.

... thus I fail to see a fundamental difference between the eval and
globals approaches, in both cases you need the name of the class.

> I am develpoing a module of which other people can make use of by
> developing their own subclasses, but they need to be instantiated by
> my code. Eval() does the trick for me or is there a better way,
> assuming you do not need to know which class it might be beforehand?

Why don't you just get your users to pass whatever class object they
want, to your code ... which can then instantiate the class.

Something like:

# Your code
class your_base:
    foo = 1

def do_something_with_user_class_instance(user_class):
    uci = user_class()
    print uci
    print dir(uci)
    return uci

# User code
class user_derived(your_base):
    def __init__(self):
        self.bar = 2

do_something_with_user_class_instance(user_derived)



More information about the Python-list mailing list