V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
luztak
V2EX  ›  Python

如何getattr独立函数(即不在类中的函数)?

  •  
  •   luztak ·
    luztak · 2013-01-31 21:24:50 +08:00 · 3262 次点击
    这是一个创建于 4074 天前的主题,其中的信息可能已经有所发展或是发生改变。
    有些函数没必要写在类里,而类需要根据输入调用这些函数......谢了先.
    4 条回复    1970-01-01 08:00:00 +08:00
    xiaket
        1
    xiaket  
       2013-01-31 22:47:29 +08:00   ❤️ 1
    func = locals().get(function_name)
    func()
    ccp0101
        2
    ccp0101  
       2013-02-01 10:51:45 +08:00
    这个函数总会属于某个父对象吧。不再类里面会在拿那个module里面。

    以下是我没有测试的代码:
    getattr(imported_module, "function_name")会返回某个已经导入的module内的函数。
    假如是同个module内调用可以用getattr(globals(), "function_name")。
    BOYPT
        3
    BOYPT  
       2013-02-01 10:56:16 +08:00
    写在另外一个类里....
    tysx
        4
    tysx  
       2013-02-01 16:45:27 +08:00
    import sys

    m = sys.modules[__name__]
    getattr(m, function_name)()
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2998 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 14:51 · PVG 22:51 · LAX 07:51 · JFK 10:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.