推荐学习书目
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
frmongo
V2EX  ›  Python

依赖字符串变量调用函数的方法?

  •  
  •   frmongo · Oct 28, 2020 · 2041 views
    This topic created in 2047 days ago, the information mentioned may be changed or developed.

    如果我有一个字符串变量 a,还有一个函数 bbb, 变量 a 的内容是 bbb 函数的名称字符串, 如何才能,仅依靠变量 a 就调用 bbb 函数(不依靠 bbb 的名字)

    a = "bbb"
    
    def bbb():
        xxx
        xxx
        return yyy
    
    bbb() # 这是传统用法,不这样用,希望在变量 a 上做文章
    
    5 replies    2020-11-10 17:53:17 +08:00
    lululau
        1
    lululau  
       Oct 28, 2020
    locals()[a]()
    JeffGe
        2
    JeffGe  
       Oct 28, 2020 via Android
    func_dict = {'bbb': bbb}

    func_dict[a]()
    zone10
        3
    zone10  
       Oct 28, 2020
    ```python
    eval(a)()
    ```

    更复杂的用 `exec()`
    dahuahua
        4
    dahuahua  
       Nov 7, 2020
    应用场景说明一下?能用户反射的地方不香吗
    frmongo
        5
    frmongo  
    OP
       Nov 10, 2020
    @dahuahua #4 现在突然想,一时想不起来场景,遇到这个需求的时候可能可以活学活用,节省一点代码
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   882 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 21:58 · PVG 05:58 · LAX 14:58 · JFK 17:58
    ♥ Do have faith in what you're doing.