【问题标题】:how to create a list of new objects in python如何在python中创建新对象列表
【发布时间】:2022-11-05 07:10:07
【问题描述】:

我正在尝试在 python 中创建一个新对象列表(如在单独的内存位置,而不是引用)

class example:
    _name = ""
    _words = []
    def __init__(self,name):
        _name = name

    def add_words(self,new_words):
        for i in new_words:
            self._words.append(i)

examples = [example("example_1"),example("example_2"),example("example_3")]
examples[0].add_words(["test1","test2"])

print(examples[2]._words)

print(examples[2]._words) 输出 ["test1","test2"] 我期待[],因为我只在examples[0] 中添加了单词

【问题讨论】:

    标签: python oop memory reference


    【解决方案1】:

    _words = [] 在班级顶部使 _words 成为班级变量,而不是实例一。所有类实例都与您现在拥有的共享_words

    改为使其成为实例变量:

    class example:
        def __init__(self,name):
            self._words = []
    
        . . .
    

    您可能还想修复_name

    【讨论】:

      【解决方案2】:

      希望这可以帮助:

      class example:
          def __init__(self, name):
              self._words = []
              self._name = name
      
          def add_words(self, new_words):
              for i in new_words:
                  self._words.append(i)
      
      
      examples = [example("example_1"), example("example_2"), example("example_3")]
      examples[0].add_words(["test1", "test2"])
      
      print(examples[2]._words)
      

      【讨论】:

        猜你喜欢
        • 2010-09-25
        • 2021-03-02
        • 1970-01-01
        • 2013-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-16
        • 1970-01-01
        相关资源
        最近更新 更多