我有一个类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")
当我打印出列表的值时,我得到 None 。
有人可以解释一下我做错了什么吗?
最佳答案
我注意到有 3 件事可能会出错:
1) 在方法 getVariableLevelDictionary 中,您试图返回 self.variableLevelDictionary,而实际上您的类“foo”没有同名的属性,这意味着当您调用此函数时,您将收到此错误:
AttributeError:“foo”对象没有属性“variableLevelDictionary”
为了解决这个问题,您可以尝试在第二个函数中执行以下操作:
self.variableLevelDictionary= {"aaa":levels,
"bbb":levels,
"ccc":levels,
"ddd":levels,
"eee":specificLevels
}
2) 当您实际上拥有 fooInstance 时,您正在调用 foo.getVariableLevelDictionary,因此也许您想调用 fooInstance.getVariableDictionary,除非您解决 1) 问题,否则它将失败
3) 您正在将某些内容分配给名为 list 的变量,该变量是列表数据结构的 Python 绑定(bind)词,不建议这样做。
您可以通过指定另一个名称来解决此问题,例如 my_list 。
让我们知道您的尝试!
关于Python 无法引用调用类中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37997596/