Search code examples
python-3.xoopstaticnameerror

Can you access a static variable in another static variable in Python


I was using a variable that i had initialized in the line before it and the console gave me the following error:

NameError: name 'Purchase' is not defined

This is my code that throws this exception

class Purchase:
   list_of_items = ["Cake", "Soap", "Jam", "Cereal", "Hand Sanitizer", "Biscuits", "Bread"]
   list_of_count_of_each_item_sold = [0] * Purchase.list_of_items

I don't understand why this happens, because when i use static variable in class method no such error ever occurs?


Solution

  • When the line list_of_count_of_each_item_sold = [0] * Purchase.list_of_items is evaluated the scope is already inside the class, so there is no need to use Purchase.list_of_items. You can directly access list_of_items:

    class Purchase:
        list_of_items = ["Cake", "Soap", "Jam", "Cereal", "Hand Sanitizer", "Biscuits", "Bread"]
        list_of_count_of_each_item_sold = [0] * list_of_items
    

    Additonally to initialize list_of_count_of_each_item_sold correctly with a 0 for each item in list_of_items you have to multiply [0] with the length of list_of_items by using len().

    class Purchase:
        list_of_items = ["Cake", "Soap", "Jam", "Cereal", "Hand Sanitizer", "Biscuits", "Bread"]
        list_of_count_of_each_item_sold = [0] * len(list_of_items)