分享

Does python have an equivalent to Java Class....

 weicat 2010-06-18

Reflection in python is a lot easier and far more flexible than it is in Java.

I recommend reading this tutorial

There's no direct function (that I know of) which takes a fully qualified class name and returns the class, however you have all the pieces needed to build that, and you can connect them together.

One advice though: don't try to program in Java style when you're in python.

If you can explain what is it that you're trying to do, maybe we can help you find a more pythonic way of doing it.

Here's a function that does what you want:

def get_class( kls ): 
    parts = kls.split('.') 
    module = ".".join(parts[:-1]) 
    m = __import__( module ) 
    for comp in parts[1:]: 
        m = getattr(m, comp)             
    return

You can use the return value of this function as if it was the class itself.

Here's a usage example:

>>> D = get_class("datetime.datetime") 
>>><type 'datetime.datetime'> 
>>> D.now() 
datetime.datetime(2009, 1, 17, 2, 15, 58, 883000) 
>>> a = D( 2010, 4, 22 ) 
>>> a 
datetime.datetime(2010, 4, 22, 0, 0) 
>>> 

How does that work?

We're using __import__ to import the module that holds the class, which required that we first extract the module name from the fully qualified name. Then we import the module:

m = __import__( module ) 

In this case, m will only refer to the top level module,

For example, if your class lives in foo.baz module, then m will be the module foo
We can easily obtain a reference to foo.baz using getattr( m, 'baz' )

To get from the top level module to the class, have to recursively use gettatr on the parts of the class name

Say for example, if you class name is foo.baz.bar.Model then we do this:

m = __import__( "foo.baz.bar" ) #m is package foo 
m = getattr( m, "baz" ) #m is package baz 
m = getattr( m, "bar" ) #m is module bar 
m = getattr( m, "Model" ) #m is class Model 

This is what's happening in this loop:

for comp in parts[1:]: 
    m = getattr(m, comp) 

At the end of the loop, m will be a reference to the class. This means that m is actually the class itslef, you can do for instance:

a = m() #instantiate a new instance of the class     
b = m( arg1, arg2 ) # pass arguments to the constructor 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多