你能在 Python 中访问另一个静态变量中的静态变量吗
Can you access a static variable in another static variable in Python
我正在使用我在它之前的行中初始化的变量,控制台给了我以下错误:
NameError: name 'Purchase' is not defined
这是我抛出此异常的代码
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
我不明白为什么会这样,因为当我在 class 方法中使用静态变量时,从来没有发生过这样的错误吗?
当行 list_of_count_of_each_item_sold = [0] * Purchase.list_of_items
被评估时,作用域已经在 class 内,所以没有必要使用 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
此外,要为 list_of_items
中的每个项目使用 0
正确初始化 list_of_count_of_each_item_sold
,您必须使用 [0]
乘以 list_of_items
的长度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)
我正在使用我在它之前的行中初始化的变量,控制台给了我以下错误:
NameError: name 'Purchase' is not defined
这是我抛出此异常的代码
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
我不明白为什么会这样,因为当我在 class 方法中使用静态变量时,从来没有发生过这样的错误吗?
当行 list_of_count_of_each_item_sold = [0] * Purchase.list_of_items
被评估时,作用域已经在 class 内,所以没有必要使用 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
此外,要为 list_of_items
中的每个项目使用 0
正确初始化 list_of_count_of_each_item_sold
,您必须使用 [0]
乘以 list_of_items
的长度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)