【问题标题】:How do I access a classes list from outside the class? [closed]如何从课堂外访问课程列表? [关闭]
【发布时间】: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 中打印了所有这些。
  • 第一句中的表达式创建了一个TestClassnew 实例,与您曾经调用过的appendToTestList 的任何实例无关。
  • 当然不是:在调用appendToTestList 之前,您从未保存对TestClass("other_variable") 创建的对象的引用。对象被创建,它的属性被附加,然后被垃圾回收。

标签: python arrays list class


【解决方案1】:

您需要先保存对对象的引用。

>>> x = TextClass("other_variable")
>>> x.appendToTestList("foo")
>>> x.appendToTestList("bar")
>>> x.testList
["foo", "bar"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多