推荐学习书目
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 · Jan 19, 2018 · 3267 views
    This topic created in 3039 days ago, the information mentioned may be changed or developed.

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

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

    有点类似于:

    def add(x,y=x):
        pass
    

    但是这么写肯定是不对的

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

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

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

    我考虑过这种情况,但是如果我指定 x 不为 None,同时 y 为 None,这么写就会有问题
    Pythonerxiaobai
        6
    Pythonerxiaobai  
       Jan 19, 2018
    @mooncakejs 那在加上判断为 0 的情况呗
    bombless
        7
    bombless  
       Jan 19, 2018
    不是 is None 么 233
    tonic
        8
    tonic  
       Jan 19, 2018
    ```
    missing = object()
    def add(x, y=missing):
    if y is missing:
    y = x
    ```
    grimpil
        9
    grimpil  
       Jan 20, 2018   ❤️ 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
       Jan 21, 2018
    @grimpil 我觉得你这个是正解了,谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2988 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 158ms · UTC 04:48 · PVG 12:48 · LAX 21:48 · JFK 00:48
    ♥ Do have faith in what you're doing.