为什么我在 运行 这个 class 时得到 NameError?
Why am I getting NameError when I run this class?
此 class、Itinerary
通过随机将各个词典放在一起来生成词典 destinations
。它还会生成一个基于概率的日期 startTime
。
这是我的代码:
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]))
然而,当我运行这个:
x = Itinerary(destinations, startTime)
print(x.destinations, 2*'\n', x.startTime)
它returns:
NameError: name 'destinations' is not defined
今天早些时候它确实有效,但后来我关闭它并重新打开它然后错误就来了。
如果这些字段是在构造函数本身中生成的,那么您的 __init__
函数不需要接受 2 个参数。
所以签名可以是:
def __init__(self): # no params in constructor
然后调用可以是:
x = Itinerary()
此 class、Itinerary
通过随机将各个词典放在一起来生成词典 destinations
。它还会生成一个基于概率的日期 startTime
。
这是我的代码:
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]))
然而,当我运行这个:
x = Itinerary(destinations, startTime)
print(x.destinations, 2*'\n', x.startTime)
它returns:
NameError: name 'destinations' is not defined
今天早些时候它确实有效,但后来我关闭它并重新打开它然后错误就来了。
如果这些字段是在构造函数本身中生成的,那么您的 __init__
函数不需要接受 2 个参数。
所以签名可以是:
def __init__(self): # no params in constructor
然后调用可以是:
x = Itinerary()