0

Here is the scenario:

I have two classes:

class A:
  pass:

class B:
  pass

Now I want to create a client, in that I need to have a small utility method, which should return my class template/object e.g: class A, class B, as I pass on the class name to that utility e.g get_obj(classA).

Now, is this possible? If then please suggest an approach, as I don't get any correct answer as of now in web.

Hope I am making sense.

3
  • make the classes an object Commented Oct 19, 2016 at 11:22
  • 1
    Yes, you can just have a dict like cls = {'classA': A, 'classB': B}, and then you can call cls.get('classA') for your get_obj implementation. This is a start though, but without much more details on what you are actually wanting to do the actual answer can be quite different. Commented Oct 19, 2016 at 11:25
  • 1
    Why do you need it? What is an empty class, that this method would return, good for? Commented Oct 19, 2016 at 11:28

3 Answers 3

2

Here is a possible implementation. All the code is contained in a single '.py' file

class A:                                                                                            
   pass                                                                                             


class B:                                                                                            
   pass                                                                                             

# map class name to class                                                                                                    
_classes = {                                                                                        
         A.__name__: A,                                                                             
         B.__name__: B,                                                                             
}                                                                                                   

def get_obj(cname):                                                                                       
    return _classes[cname]()                                                                            

# test the function                                                                                                    
if __name__ == '__main__':                                                                          
   print get_obj('A')   

It will produce the following output

<__main__.A instance at 0x1026ea950>
Sign up to request clarification or add additional context in comments.

Comments

0

Standard library function namedtuple creates and returns a class. Internally it uses exec. It may be an inspiration for what you need.

Source code: https://github.com/python/cpython/blob/master/Lib/collections/init.py#L356

3 Comments

It's funny that people are downvoting this answer considering that the designers of the language themselves seemingly have no problem using exec for this kind of thing.
@RickTeachey I've downvoted it, because question is not about defining class. Is about defining small utility method, which should return my class template/object e.g: class A, class B, as I pass on the class name to that utility.
I think we need more clarification from the original asker what should it really do. Whether he wants just a dict lookup like in @AnthonyKong's answer or something more dynamic.
0

globals() returns a dictionary containing all symbols defined in the global scope of the module (including classes A and B):

a_and_b_module.py

class A: pass
class B: pass

def get_cls(cls_name):
    return globals()[cls_name]

If you are looking for simplicity

If the code that will call this function is inside the module, then you can eliminate the function altogether and use globals()[cls_name] directly.

If the code that will call this function is outside the module, then you could use getattr function:

a_and_b_module.py

class A: pass
class B: pass

another_file.py

import a_and_b_module

cls_name = 'A'
chosen_cls = getattr(a_and_b_module, cls_name)

If you are looking for complete control

The problem with the approach above is that it could return anything defined in a_and_b_module.py, not restricting itself to A and B. If you want to make sure only A and B can be returned:

class A: pass
class B: pass

allowed_classes = ('A', 'B')

def get_cls(cls_name):
    assert cls_name in allowed_classes
    return globals()[cls_name]

Note: you might also be interested in the concept of factory.

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.