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

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

  •  
  •   fghjghf · 2019-08-08 18:16:50 +08:00 · 3205 次点击
    这是一个创建于 1715 天前的主题,其中的信息可能已经有所发展或是发生改变。

    前提: 基于 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 条回复    2019-08-09 01:38:09 +08:00
    Trim21
        1
    Trim21  
       2019-08-08 18:21:31 +08:00 via Android
    def my_lpush(key: str, container: list):
    redis_conn.lpush(key, *container)


    你问的莫非是这个?
    fghjghf
        2
    fghjghf  
    OP
       2019-08-08 20:50:06 +08:00
    @Trim21 对对对,就是这个,dalao 怎么处理的
    believeMe
        3
    believeMe  
       2019-08-08 21:02:04 +08:00
    @fghjghf #2 大佬 加个好友
    Trim21
        4
    Trim21  
       2019-08-08 21:03:02 +08:00
    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  
       2019-08-08 21:04:14 +08:00
    晕死, 基本的教程上就有的东西, 感情都不看直接撸的么?
    aheadlead
        6
    aheadlead  
       2019-08-08 21:10:43 +08:00
    @AlvaIM #5 这个还好吧,有时这种问题也确实不知道怎么 google
    fghjghf
        7
    fghjghf  
    OP
       2019-08-08 21:15:09 +08:00
    @Trim21 @AlvaIM 谢谢大佬,没仔细看语法,直接上手的,遇到问题在往回看
    2DaYe
        8
    2DaYe  
       2019-08-09 01:38:09 +08:00
    4 楼正解

    def func(*args, **kwargs):
    print(args, kwargs)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5474 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 06:36 · PVG 14:36 · LAX 23:36 · JFK 02:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.