ITeye博客

python 反射

pypy · 2012-03-20 10:31 · python · 互联网 · Python · Linux · Markdown

如何在python中实现 类似java中,[code="java"]Class.forName().newInstance()[/code]的功能 1. 静态导入 [code="python"]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__': , '__name__': '__main__', 'time': , '__doc__': None, '__package__': None} >>> globals()["time"] >>> [/code] 如果不显示导入 from time import time,会报异常, [code="python"]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__': , '__name__': '__main__', '__doc__': None, '__package__': None} >>> globals()["time"] Traceback (most recent call last): File "", line 1, in KeyError: 'time' >>>[/code] 2. 动态导入 [code="python"]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 >>> se_time=getattr(module, "time") >>> se_time >>> se_time() 1332210676.294227 >>>[/code] [code="python"]name=self.__class__.__name__[/code]

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。