I have a class MyClass which stores an integer a. I want to define a function inside it that takes a numpy array x of length a, but I want that if the user does not pass in anything, x is set to a random array of the same length. (If they pass in values of the wrong length, I can raise an error). Basically, I would like x to default to a random array of size a.
Here is my attempt at implementing this
import numpy as np
class MyClass():
def __init__(self, a):
self.a = a
def function(self, x = None):
if x == None:
x = np.random.rand(self.a)
# do some more functiony stuff with x
This works if nothing is passed in, but if x is passed in I get ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() i.e. it seems numpy doesn't like comparing arrays with None.
Defining the default value inline doesn't work because self is not in scope yet.
Is there a nice pythonic way to achieve this? To sum up I would like the parameter x to default to a random array of a specific, class-defined length.
==test on an array. Such a test produces a boolean array of the same size. Doesif [True,False,True,False]:make sense? Fortunately in this caseis Noneis the right alternative.