Python无法引用调用类中的列表

2024-04-19 10:00:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类foo,其中有这两个方法。variableLevelDictionary是一个字典,字符串作为键,列表作为值。你知道吗

class foo:


levels = []
specificLevels = []
variableLevelDictionary = {}

def __init__(self):
    self.createDictionaryOfVariableAndLevel()

  def getVariableLevelDictionary(self):
    return self.variableLevelDictionary

  def createDictionaryOfVariableAndLevel(self):

    variableList =  self.listOfVariables()
    levels = self.getAllLevels()
    specificLevels=self.getSpecicficLevels()
    variableLevelDictionary = {"aaa":levels,
                               "bbb":levels,
                               "ccc":levels,
                               "ddd":levels,
                               "eee":specificLevels
                               }

在主模块的main()函数中,我实例化foo,然后调用这个方法

global variableLevelDictionary
fooInstance = foo()
variableLevelDictionary =fooInstance.getVariableLevelDictionary()

然后我就这么做了

list = variableLevelDictionary.get("aaa")

当我打印出list的值时,我没有得到任何结果。你知道吗

有人能解释一下我做错了什么吗?你知道吗


Tags: 方法字符串self列表字典foodeflist
1条回答
网友
1楼 · 发布于 2024-04-19 10:00:44

我注意到有三件事可能会出错:

1)在方法getVariableLevelDictionary中,您尝试返回自变量leveldictionary实际上,当类“foo”没有同名属性时,这意味着调用此函数时将出现以下错误:

AttributeError:“foo”对象没有“variableLevelDictionary”属性

为了解决这个问题,您可以尝试在第二个函数中执行以下操作:

self.variableLevelDictionary= {"aaa":levels,
                               "bbb":levels,
                               "ccc":levels,
                               "ddd":levels,
                               "eee":specificLevels
                               }

2)你在打电话foo.getVariableLevelDictionary版本当事实上你有foodInstance的时候,也许你想打电话给fooInstance.getVariableDictionary,除非你解决1)

3)您正在为名为list的变量赋值,该变量是列表数据结构的Python绑定词,不建议这样做。你知道吗

您可以通过指定另一个名称来解决这个问题,也许我的\u列表。你知道吗

让我们知道你尝试了什么!你知道吗

相关问题 更多 >