【问题标题】:Why am I getting NameError when I run this class?为什么我在运行此类时收到 NameError?
【发布时间】:2020-08-09 19:00:48
【问题描述】:

这个类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)

它返回: NameError: name 'destinations' is not defined

它实际上在今天早些时候工作,但后来我关闭它并重新打开它,然后错误来了。

【问题讨论】:

  • destinations 在哪里定义 x = Itinerary(destinations, startTime)

标签: python class attributes nameerror


【解决方案1】:

如果这些字段是在构造函数本身中生成的,那么您的 __init__ 函数不需要接受 2 个参数。 所以签名可以是:

def __init__(self): # no params in constructor

然后调用可能是:

x = Itinerary()

【讨论】:

    猜你喜欢
    • 2010-09-15
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多