Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/svn/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 共依赖缺省参数_Python - Fatal编程技术网

Python 共依赖缺省参数

Python 共依赖缺省参数,python,Python,我有这样的代码: import random def helper(): c = random.choice([False, True]), d = 1 if (c == True) else random.choice([1, 2, 3]) return c, d class Cubic(object): global coefficients_bound def __init__(self, a = random.choice([False, T

我有这样的代码:

import random

def helper():
    c = random.choice([False, True]),
    d = 1 if (c == True) else random.choice([1, 2, 3])
    return c, d

class Cubic(object):
    global coefficients_bound

    def __init__(self, a = random.choice([False, True]), 
        b = random.choice([False, True]),
        (c, d) = helper()):
        ...
        ...
helper()函数的引入是因为我不能在函数本身的定义中使用共依赖参数——Python抱怨它在计算d时找不到c

我希望能够像这样创建此类的对象,更改默认参数:

x = Cubic(c = False)
但我得到了这个错误:

Traceback (most recent call last):
  File "cubic.py", line 41, in <module>
    x = Cubic(c = False)
TypeError: __init__() got an unexpected keyword argument 'c'
回溯(最近一次呼叫最后一次):
文件“cubic.py”,第41行,在
x=立方(c=假)
TypeError:\uuuu init\uuuuuuuuu()获取了意外的关键字参数“c”
我是怎么写的,这可能吗?如果没有,我应该怎么做?

简单地说:

class Cubic(object):
    def __init__(self, c=None, d=None):
        if c is None:
            c = random.choice([False, True])
        if d is None:
            d = 1 if c else random.choice([1, 2, 3])
        print c, d

我怀疑这是否会像您所想的那样起作用-在创建函数时会选择一个调用
random.choice()
的默认参数,然后每次调用它时都会选择相同的参数@谢谢你的提醒。我以前读过这篇文章,但我没有考虑使用random时的关联性。choice+1-OP似乎把它复杂化了。请注意,PEP-8建议不要在默认参数中使用空格
=
。@Lattyware操作确实使其过于复杂。也感谢您关于PEP-8的留言。