【问题标题】:Is it possible for objects of a class to have the same reference of a class attribute that they are in?一个类的对象是否有可能与它们所在的类属性具有相同的引用?
【发布时间】:2023-03-14 00:10:02
【问题描述】:

我不知道我的问题是否过于混乱甚至正确,所以为了清楚起见,这里有一个例子:

class Parent():
  def __init__(self,addr):
    self.addr = addr
    self.child1 = Child(self.addr)
    self.child2 = Child(self.addr)

class Child():
  def __init__(self,addr):
    self.addr = addr

parent = Parent('USA')

我想要完成的是,每当我更改 Parent 对象的 addr 属性时,child1child2 内部的 Parent 对象的 addr 属性也会更改。

parent.child1.addr >>> 'USA'

但是当我更改 Parent 对象时,Parent.child1 保持不变。

parent.addr = 'France'

parent.child1.addr >>> 'USA'
parent.addr >>>'France'

【问题讨论】:

    标签: python python-3.x oop


    【解决方案1】:

    您可以将Child.addr 设为property,以获取父级的addr

    class Parent:
        def __init__(self, addr):
            self.addr = addr
            self.child1 = Child(self)
            self.child2 = Child(self)
    
    
    class Child:
        def __init__(self, parent):
            self.parent = parent
    
        @property
        def addr(self):
            return self.parent.addr
    

    【讨论】:

      【解决方案2】:

      另一种方法是在 Parent 类中使用 addr 而不是 self.addr。

      例子:

      class Parent():
        def __init__(self,addr):
          self.addr = addr
          self.child1 = Child(addr) 
          self.child2 = Child(addr) 
      
      class Child():
        def __init__(self,addr):
          self.addr = addr
      
      parent = Parent('USA')
      

      输出: parent.child1.addr 是 'USA'

      parent.addr = 'France'
      

      输出: parent.addr 是 'France'

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-10
        • 2022-01-20
        • 1970-01-01
        相关资源
        最近更新 更多