2

how do i create object-instances on runtime in python?

say i have 2 classes:

class MyClassA(object):
    def __init__(self, prop):
        self.prop = prop
        self.name = "CLASS A"

    def println(self):
        print self.name


class MyClassB(object):
    def __init__(self, prop):
        self.prop = prop
        self.name = "CLASS B"

    def println(self):
        print self.name

and a dict

{('a': MyClassA), ('b': MyClassB)}

how can i create dynamic an instance of one of my two classes, depending of i choose 'a' or 'b'.

kind of this:

somefunc(str):
    if 'a': return new MyClassA
    if 'b': return new MyClassB

to get "CLASS B" on calling: somefunc('a').println

but in a more elegant and dynamic way (say i add more classes to the dict on runtime)

2 Answers 2

6

You might create a dispatcher, which is a dictionary with your keys mapping to classes.

dispatch = {
    "a": MyClassA,
    "b": MyClassB,
}

instance = dispatch[which_one]() # Notice the second pair of parens here!
Sign up to request clarification or add additional context in comments.

Comments

2

You create a class instance by calling the class. Your class dict {('a': MyClassA), ('b': MyClassB)} returns classes; so you need only call the class:

classes['a']()

But I get the sense you want something more specific. Here's a subclass of dict that, when called with a key, looks up the associated item and calls it:

>>> class ClassMap(dict):
...     def __call__(self, key, *args, **kwargs):
...         return self.__getitem__(key)(*args, **kwargs)
... 
>>> c = ClassMap()
>>> c['a'] = A
>>> c['b'] = B
>>> c('a')
<__main__.A object at 0x1004cc7d0>

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.