2

I have code like so:

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()):
        ...
        ...

The helper() function is introduced as I cannot have co-dependent arguments in the definition of the function itself - Python complains that it cannot find c when it's calculating d.

I want to be able to create an object of this class like so, changing a default argument:

x = Cubic(c = False)

But I get this error:

Traceback (most recent call last):
  File "cubic.py", line 41, in <module>
    x = Cubic(c = False)
TypeError: __init__() got an unexpected keyword argument 'c'

Is this possible with how I've written it? If not, what way should I do this?

nebffa
  • 1,529
  • 1
  • 16
  • 26
  • 5
    I doubt this works how you think it will - a default argument calling `random.choice()` will be picked when the function is created, and then be the same every time it is called. [This question explains why.](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument). – Gareth Latty Apr 02 '13 at 09:43
  • @Lattyware thanks for the reminder. I have read that before but I didn't think about the relevance when using random.choice – nebffa Apr 02 '13 at 10:11

1 Answers1

6

How about simply:

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
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 2
    +1 - OP appears to have overcomplicated this. Note that PEP-8 recommends against spaces either side of the `=` in default arguments. – Gareth Latty Apr 02 '13 at 09:46
  • @Lattyware the OP has overcomplicated it indeed. Thanks for your note about PEP-8 also. – nebffa Apr 02 '13 at 10:10