推荐学习书目
› 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 · Jan 31, 2013 · 4554 views
    This topic created in 4991 days ago, the information mentioned may be changed or developed.
    有些函数没必要写在类里,而类需要根据输入调用这些函数......谢了先.
    4 replies  •  1970-01-01 08:00:00 +08:00
    xiaket
        1
    xiaket  
       Jan 31, 2013   ❤️ 1
    func = locals().get(function_name)
    func()
    ccp0101
        2
    ccp0101  
       Feb 1, 2013
    这个函数总会属于某个父对象吧。不再类里面会在拿那个module里面。

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

    m = sys.modules[__name__]
    getattr(m, function_name)()
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2356 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 11:50 · PVG 19:50 · LAX 04:50 · JFK 07:50
    ♥ Do have faith in what you're doing.