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
DaVinci42
V2EX  ›  Python

求教 Python 交互式编程

  •  
  •   DaVinci42 · 2015-04-22 01:05:18 +08:00 · 2772 次点击
    这是一个创建于 3317 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如说,已经定义了 print_a(), print_b(), print_c() 等函数,

    功能是输出a, b, c。

    需求:用户输入print_a,自动调用 print_a 函数,其他同理

    现在的思路是,
    如果输入内容==“print_a”,那么执行 print_a,其他同理,
    都不符合,提示输入错误。

    但现在需要大量的判断语句(判断输入是否为某某字符串)

    希望实现:创建一个所有函数的列表,if 输入字符 in 函数列表,执行对应函数;else 提示输入错误。
    遇到的问题是,用变量表示函数是否在列表中比较容易,但是如何用变量调用具体的函数。

    能否提供思路,谢谢。


    啊,其实我想用 Python 玩儿一下魔方,
    所以需要定义一堆基本R, L, U, F 等函数,输入字母即可执行对应操作
    8 条回复    2015-04-22 10:33:17 +08:00
    14
        1
    14  
       2015-04-22 01:12:48 +08:00   ❤️ 1
    func_map = {
    'print_a': print_a,
    'print_b': print_a,
    }

    s = 'print_a'
    func = func_map[s]
    gateswong
        3
    gateswong  
       2015-04-22 01:17:48 +08:00   ❤️ 2
    DaVinci42
        4
    DaVinci42  
    OP
       2015-04-22 01:42:10 +08:00
    @14 谢谢,没有想到用字典关联字符串与函数;
    @Sylv 谢谢,是我英文 Google 还不够准确;
    @gateswong 谢谢,if __name__ == '__main__' 这行确实非常有用!
    twor2
        5
    twor2  
       2015-04-22 01:48:22 +08:00
    ```
    input() uses raw_input to read a string of data, and then attempts to evaluate it as if it were a Python program, and then returns the value that results. So entering
    ```
    wizardforcel
        6
    wizardforcel  
       2015-04-22 08:19:31 +08:00 via Android
    动态调用么。用eval吧

    funcName ="print_a"
    eval(funcName)()
    JoeShu
        7
    JoeShu  
       2015-04-22 10:03:24 +08:00
    应该安装1楼的方式,用字典代替switch语句,其他的输入直接执行和调用eval的都不要信,会有很严重的安全问题。
    DaVinci42
        8
    DaVinci42  
    OP
       2015-04-22 10:33:17 +08:00
    @JoeShu 谢谢,了解了一下,eval 是有用户恶意使用的问题
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3144 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 11:01 · PVG 19:01 · LAX 04:01 · JFK 07:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.