简体   繁体   English

为什么在 python 中定义变量后出现名称错误?

[英]Why am I getting a name error after defining the a variable in python?

class HashMap:
  def __init__(self, array_size):
    self.array_size = size
    self.array = [LinkedList() for number in range(array_size)]

I wrote the above code and it shows the following error:我写了上面的代码,它显示了以下错误:

 File "script.py", line 7, in __init__
    self.array_size = size
NameError: name 'size' is not defined

You are getting this error because you are referring to non existent variable size .您收到此错误是因为您指的是不存在的变量size

Your variable array_size will get its value when instantiated from outside and the same can be used internally as such.当从外部实例化时,您的变量array_size将获得它的值,并且可以在内部使用相同的值。 However, if you plan to modify it, first assign it to another variable and then modify the new variable, eg,但是,如果您打算修改它,请先将其分配给另一个变量,然后修改新变量,例如,

size = array_size
size = size + 1 

But, in the context of the code you have posted, you apparently do not need any additional variable other than self_array being used for storing list of LinkedList objects.但是,在您发布的代码的上下文中,除了用于存储 LinkedList 对象列表的self_array之外,您显然不需要任何其他变量。

I have reproduced your code (commenting out erroneous code), with a place-holder LinkedList class and it runs without giving any error.我已经使用占位符 LinkedList class 复制了您的代码(注释掉错误代码),并且它运行时没有给出任何错误。

class LinkedList:
    def __init__(self):
        self.start_node = None


class HashMap:
    def __init__(self, array_size):
        #self.array_size = size
        self.array = [LinkedList() for number in range(array_size)]

a = HashMap(20)

print (len(a.array))

The output is: output 是:

20

Hope it helps希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM