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

Python 如何动态生成变量后动态调用函数

  •  
  •   fghjghf · Aug 8, 2019 · 4192 views
    This topic created in 2610 days ago, the information mentioned may be changed or developed.

    前提: 基于 redis 的封装,例如在 list 的 rpush 和 lpush,参数只能单个的传送。不支持 list,dict,tuple .如果传了就报错:redis.exceptions.DataError: Invalid input of type: 'list'. Convert to a byte, string or number first.

    因为是二次封装,如何动态生成变量,然后作为入参动态调用 redis 函数。

    8 replies  •  2019-08-09 01:38:09 +08:00
    Trim21
        1
    Trim21  
       Aug 8, 2019 via Android
    def my_lpush(key: str, container: list):
    redis_conn.lpush(key, *container)


    你问的莫非是这个?
    fghjghf
        2
    fghjghf  
    OP
       Aug 8, 2019
    @Trim21 对对对,就是这个,dalao 怎么处理的
    PRD
        3
    PRD  
       Aug 8, 2019
    @fghjghf #2 大佬 加个好友
    Trim21
        4
    Trim21  
       Aug 8, 2019
    list 和 tuple 你在调用的时候就直接前面加一个星号就好了, 这是 python 的某个语法, 会直接把可迭代对象展开传给函数

    redis_conn.lpush(key, *container)

    你这么调用, 就会把 container 里面所有的元素 lpush 到对应的 redis 列表里面

    比如 container==['1','2','3']

    就会转化成 redis 的 LPUSH ${key} '1' '2' '3'这条命令

    dict 的话还要额外处理一下, 我也不知道你到底要传什么进去.
    AlvaIM
        5
    AlvaIM  
       Aug 8, 2019
    晕死, 基本的教程上就有的东西, 感情都不看直接撸的么?
    aheadlead
        6
    aheadlead  
       Aug 8, 2019
    @AlvaIM #5 这个还好吧,有时这种问题也确实不知道怎么 google
    fghjghf
        7
    fghjghf  
    OP
       Aug 8, 2019
    @Trim21 @AlvaIM 谢谢大佬,没仔细看语法,直接上手的,遇到问题在往回看
    2DaYe
        8
    2DaYe  
       Aug 9, 2019
    4 楼正解

    def func(*args, **kwargs):
    print(args, kwargs)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2430 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 08:01 · PVG 16:01 · LAX 01:01 · JFK 04:01
    ♥ Do have faith in what you're doing.