【发布时间】:2021-04-09 02:59:05
【问题描述】:
我尝试使用TestClass("other_variable").testList 从班级外部访问班级列表,但它不起作用,它返回[]。
这是我的代码:
class TestClass:
def __init__(self, other_variable):
self.other_variable = other_variable
self.testList = []
def appendToTestList(self, string):
self.testList.append(string)
print(self.testList) # This works, it prints the full list.
我写了一个函数,希望它会返回列表,但它只是返回相同的东西([]):
def showTestList(self):
return self.testList # Returns []
【问题讨论】:
-
在打电话给
showTestList之前你有没有打电话给appendToTestList? -
是的。多次,并在 appendToTestList 中打印了所有这些。
-
第一句中的表达式创建了一个
TestClass的new 实例,与您曾经调用过的appendToTestList的任何实例无关。 -
当然不是:在调用
appendToTestList之前,您从未保存对TestClass("other_variable")创建的对象的引用。对象被创建,它的属性被附加,然后被垃圾回收。