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

菜鸟请教一个有关函数的默认参数的问题

  •  
  •   hjq98765 · 2018-01-19 16:56:46 +08:00 · 2214 次点击
    这是一个创建于 2260 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在有一个函数 func,有两个参数 x,y,其中 x 是必选参数,y 是可选参数

    我的想法是:当参数 y 没有传入值的时候,参数 y 的值默认等于参数 x 的值

    有点类似于:

    def add(x,y=x):
        pass
    

    但是这么写肯定是不对的

    所以应当怎么实现我的想法呢?

    10 条回复    2018-01-21 12:44:39 +08:00
    crab
        1
    crab  
       2018-01-19 17:00:06 +08:00
    在函数内判断 Y 是否 None,再赋值是否可行?
    Pythonerxiaobai
        2
    Pythonerxiaobai  
       2018-01-19 17:00:40 +08:00   ❤️ 1
    def add(x, y=None):
    if not y:
    y = x

    return x + y
    yujieyu7
        3
    yujieyu7  
       2018-01-19 17:01:59 +08:00
    不求优雅的话,函数内自己判断和赋值吧
    mooncakejs
        4
    mooncakejs  
       2018-01-19 17:07:02 +08:00   ❤️ 1
    @Pythonerxiaobai add(1,0) 卒
    hjq98765
        5
    hjq98765  
    OP
       2018-01-19 17:08:59 +08:00
    @crab
    @Pythonerxiaobai

    我考虑过这种情况,但是如果我指定 x 不为 None,同时 y 为 None,这么写就会有问题
    Pythonerxiaobai
        6
    Pythonerxiaobai  
       2018-01-19 17:15:22 +08:00
    @mooncakejs 那在加上判断为 0 的情况呗
    bombless
        7
    bombless  
       2018-01-19 17:17:25 +08:00
    不是 is None 么 233
    tonic
        8
    tonic  
       2018-01-19 17:23:52 +08:00
    ```
    missing = object()
    def add(x, y=missing):
    if y is missing:
    y = x
    ```
    grimpil
        9
    grimpil  
       2018-01-20 10:18:59 +08:00   ❤️ 1
    不知道这样可以不


    def f(x, *arg):
    if len(arg) == 0:
    y = x
    f(x,y)
    elif len(arg) == 1:
    y = arg[0]
    pass
    hjq98765
        10
    hjq98765  
    OP
       2018-01-21 12:44:39 +08:00
    @grimpil 我觉得你这个是正解了,谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3212 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 13:07 · PVG 21:07 · LAX 06:07 · JFK 09:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.