Search code examples
pythonclassattributesnameerror

Why am I getting NameError when I run this class?


This class, Itinerary, generates a dictionary destinations by putting together individual dictionaries at random. It also generates a date startTime which is based on probabilities.

Here is my code:

class Itinerary:
    def __init__(self, destinations, startTime):
        self.destinations = {**a, **np.random.choice([b1,b2]), **np.random.choice([c1,c2,c3,c4]), 
                             **np.random.choice([d1,d2,d3]), **np.random.choice([e1,e2]), **f1, **g, 
                             **np.random.choice([h1,h2,h3]), **i}
        self.startTime = datetime(year = 2020, 
                                  month = np.random.choice(list(range(1,13)), p = [0.0657, 0.0755, 
                                                                                   0.081, 0.067, 
                                                                                   0.0751, 0.1031, 
                                                                                   0.1178, 0.1155, 
                                                                                   0.0858, 0.0806, 
                                                                                   0.0655, 0.0674]), 
                                  day = np.random.choice(list(range(1,30))), 
                                  hour = np.random.choice([9,12], p = [0.3, 0.7]))

However, when I run this:

x = Itinerary(destinations, startTime)

print(x.destinations, 2*'\n', x.startTime)

it returns: NameError: name 'destinations' is not defined

It actually worked earlier today, but then I closed it and reopened it and then the error came.


Solution

  • Your __init__ function doesn't need to take in 2 parameters if those fields are generated within the constructor itself. So the signature can be:

    def __init__(self): # no params in constructor
    

    and then the call could be:

    x = Itinerary()