- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert a string to a Python class object?
Given a string as user input to a Python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace.
Example
class Foobar: pass print eval("Foobar") print type(Foobar)
Output
__main__.Foobar <type 'classobj'>
Another way to convert a string to class object is as follows
Example
import sys class Foobar: pass def str_to_class(str): return getattr(sys.modules[__name__], str) print str_to_class("Foobar") print type(Foobar)
Output
__main__.Foobar <type 'classobj'>
Advertisements