Home  >  Article  >  Java  >  How to Dynamically Instantiate Classes in Python: Is There a Class.forName() Equivalent?

How to Dynamically Instantiate Classes in Python: Is There a Class.forName() Equivalent?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 11:32:03277browse

How to Dynamically Instantiate Classes in Python: Is There a Class.forName() Equivalent?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn