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

Python 怎么定义 class do_something(do_what=arg_a)这样的接受传入参数有等号类?

  •  
  •   ladypxy · 2019-08-17 05:59:23 +08:00 · 2160 次点击
    这是一个创建于 1685 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如题,这种有等号的应该怎么处理。要实现的是根据等号前后不同,可以执行不同的命令。 比如 do_something(do_print=“ a ”): print(“ a ”) do_something(do_list=“ b ”): print(“ b ”)

    7 条回复    2019-08-17 20:06:02 +08:00
    wgq2633
        1
    wgq2633  
       2019-08-17 06:14:45 +08:00 via Android
    我暂时用函数说一下我的思路,不理解 LZ 为什么要用类。

    def do_something(**kwargs):
    if "do_print" in kwargs:
    print(kwargs[do_print"])
    if "do_list" in kwargs:
    print(kwargs[do_list"])
    不知道能否满足楼主需求
    关键字 “可变参数 关键字参数”可直达。
    jw19961019
        2
    jw19961019  
       2019-08-17 06:59:55 +08:00 via Android
    看基础吧。别拿其他语言在 Python 里瞎弄。class 有多种定义方式。
    leishi1313
        3
    leishi1313  
       2019-08-17 07:11:10 +08:00
    建议搜索一下“ X Y Problem ”
    renmu123
        4
    renmu123  
       2019-08-17 07:56:06 +08:00 via Android
    简单直接传进来匿名函数
    ladypxy
        5
    ladypxy  
    OP
       2019-08-17 08:00:11 +08:00
    @wgq2633 感谢。目的是写个 api,通过传入不同的参数,然后根据等号左侧的部分,来进行不同的操作。
    jmc891205
        6
    jmc891205  
       2019-08-17 13:21:20 +08:00
    Python 没有重载构造函数
    可以给参数默认值自己去实现
    或者使用 classmethod 自己定义另外的用来构造一个对象的函数
    j0hnj
        7
    j0hnj  
       2019-08-17 20:06:02 +08:00 via iPhone
    元类 metaclass
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   934 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 20:58 · PVG 04:58 · LAX 13:58 · JFK 16:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.