【问题标题】:Can you access a static variable in another static variable in Python你可以在 Python 的另一个静态变量中访问一个静态变量吗
【发布时间】:2020-08-30 14:57:49
【问题描述】:

我使用了一个我在它之前的行中初始化的变量,控制台给了我以下错误:

NameError:未定义名称“Purchase”

这是我抛出此异常的代码

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

我不明白为什么会这样,因为当我在类方法中使用静态变量时,从来没有发生过这样的错误?

【问题讨论】:

    标签: python-3.x oop static nameerror


    【解决方案1】:

    list_of_count_of_each_item_sold = [0] * Purchase.list_of_items 行被评估时,范围已经在类内,所以不需要使用Purchase.list_of_items。可以直接访问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
    

    此外,要使用0list_of_items 中的每个项目正确初始化list_of_count_of_each_item_sold,您必须使用len()[0]list_of_items 的长度相乘。

    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)
    

    【讨论】:

      猜你喜欢
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 2016-11-10
      相关资源
      最近更新 更多