我有这样的代码:
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()):
...
...
Run Code Online (Sandbox Code Playgroud)
引入了helper()函数,因为我在函数本身的定义中没有共同依赖的参数 - Python抱怨它在计算d时找不到c.
我希望能够像这样创建这个类的对象,更改默认参数:
x = Cubic(c = False)
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误:
Traceback (most recent call last):
File "cubic.py", line 41, in <module>
x = Cubic(c = False)
TypeError: __init__() got an unexpected keyword argument 'c'
Run Code Online (Sandbox Code Playgroud)
这可能与我写的方式有关吗?如果没有,我应该怎样做?
怎么样简单:
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
Run Code Online (Sandbox Code Playgroud)