简体   繁体   中英

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 .

Your variable array_size will get its value when instantiated from outside and the same can be used internally as such. 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.

I have reproduced your code (commenting out erroneous code), with a place-holder LinkedList class and it runs without giving any error.

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:

20

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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