【问题标题】:Python, the parent changes when using append list to change the child content [duplicate]Python,使用附加列表更改子内容时父级更改[重复]
【发布时间】:2020-08-06 03:17:16
【问题描述】:

我正在尝试使用 append 将变量添加到 Python 中的子级,同时更改子级中的列表会修改父级。示例代码:

class parent:
    A=[1,2,3]

class child(parent):
     pass

child.A.append('new variable')
parent.A

输出为:[1, 2, 3, 'new variable']

虽然我期望拥有:[1, 2, 3] 如何在不更改父级的情况下编辑子级列表(假设我不允许更改父级,所以我不能使用实例)?

【问题讨论】:

  • 您可以使列表成为实例变量而不是类变量。
  • A 不存在于child__dict__ 属性中,因此child.A 解析为parent.A
  • 不,这只是附加的问题。如果我有一个字符串而不是列表,那么它是独立的
  • 是的;那是因为您无法对就地修改它的字符串做任何事情,您只能替换它。当您在列表上使用.append 时,它是同一个对象,只是它的内容发生了变化。通过分配给child.A,您不会替换parent.A,而是创建附加到child 的单独A 属性。

标签: python inheritance append


【解决方案1】:

基本上是名字修改的问题

A 类: def init(自我,姓名): self.__name = 名称

def print_name(self):
    print self.__name


class B(A):
    def __init__(self, name):
        A.__init__(self, name)
        self.__name = name + "yes"

    def print_name(self):
        print self.__name

    def print_super_name(self):
        print self._A__name #class name mangled into attribute

检查下面链接中给出的答案 Subclass variables with the same name of superclass ones

【讨论】:

  • 我认为这个答案可能是为了另一个问题?
  • 我的理解是要求分离父子变量的问题。
猜你喜欢
  • 2012-11-08
  • 2014-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多