1

Say we have a python file with:

class A(object):
    def say_hi(self):
        print('hi, I am A')


class B(object):
    def say_hi(self):
        print('hi, I am B')


class F(object):
    def __init__(self, name):
        self.name = name

    def create(self):
        return  ## ???


if __name__ == '__main__':
    f = F('B')
    b = f.create()
    b.say_hi()

And I want create instance of a class with its name. What the code in F.create() should be?

4
  • 2
    globals()[self.name]() ? Commented Jan 10, 2014 at 4:29
  • @thefourtheye well, If I pass 'A', I want a A() if 'B' then B(). Commented Jan 10, 2014 at 4:31
  • @DSM 'cause I need create instances base on a config file in which the class name is given. Commented Jan 10, 2014 at 4:43
  • @mitnk: ah, sorry. I misread the problem. I thought you were creating instances and binding them to a given name, but instead you're accessing objects. That's perfectly sensible. Commented Jan 10, 2014 at 4:44

1 Answer 1

3

Use globals:

>>> class A(object):
...     def say_hi(self):
...         print('hi, I am A')
...
>>> class B(object):
...     def say_hi(self):
...         print('hi, I am B')
...
>>> class F(object):
...     def __init__(self, name):
...         self.name = name
...     def create(self):
...         return globals()[self.name]()
...
>>>
>>> f = F('B')
>>> b = f.create()
>>> b.say_hi()
hi, I am B
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I always think it's sort of evil to use globals or locals in python. So it not evil at all (at least in the code here)?
@mitnk, If you want to restrict name to A, B, use something like {'A': A, 'B': B}[self.name]().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.