Does Python Offer an Equivalent to Java's Class.forName() Method?
Python's reflection capabilities are more extensive and flexible compared to Java's. This article addresses the question of whether Python has an equivalent to Java's Class.forName(), and provides a Pythonic solution to dynamically instantiating classes from string arguments.
Reflecting upon Java's Class.forName() method, which takes a fully qualified class name as input and returns the corresponding class object, one can envision a similar functionality in Python. However, Python does not have a direct equivalent.
The get_class() function presented below emulates the behavior of Class.forName(), enabling the creation of class objects from string representations:
<code class="python">def get_class(kls): parts = kls.split('.') module = ".".join(parts[:-1]) m = __import__(module) for comp in parts[1:]: m = getattr(m, comp) return m</code>
This function can be used as if it were the class itself.
For instance, consider the following:
<code class="python">D = get_class("datetime.datetime") D # Output: <type 'datetime.datetime'> D.now() # Output: datetime.datetime(2009, 1, 17, 2, 15, 58, 883000) a = D(2010, 4, 22) a # Output: datetime.datetime(2010, 4, 22, 0, 0)</code>
Moreover, the article highlights the differences in Python's reflection compared to Java's, and encourages the exploration of Pythonic approaches to achieve similar functionality.
The above is the detailed content of How to Dynamically Instantiate Classes in Python: Is There a Class.forName() Equivalent?. For more information, please follow other related articles on the PHP Chinese website!