python 反射

如何在python中实现 类似java中,
Class.forName().newInstance()
的功能

1.静态导入

tommy@ubuntu:~$ python
Python 2.7.2+ (default, Oct  4 2011, 20:03:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from time import time
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'time': <built-in function time>, '__doc__': None, '__package__': None}
>>> globals()["time"]
<built-in function time>
>>>

如果不显示导入fromtimeimporttime,会报异常,

tommy@ubuntu:~$ python
Python 2.7.2+ (default, Oct  4 2011, 20:03:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> globals()["time"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'time'
>>>

2.动态导入

tommy@ubuntu:~$ python
Python 2.7.2+ (default, Oct  4 2011, 20:03:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> module=__import__('time')
>>> module
<module 'time' (built-in)>
>>> se_time=getattr(module, "time")
>>> se_time
<built-in function time>
>>> se_time()
1332210676.294227
>>>
name=self.__class__.__name__

相关推荐