Is it possible for objects of a class to have the same reference of a class attribute that they are in?

Viewed 60

I don't know if my question is too confusing or even correct, so to make it clear here's an example:

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')

What I want to accomplish is whenever I change the addr attribute of the Parent object the addr attribute of child1 and child2 objects inside of Parent are also changed.

parent.child1.addr >>> 'USA'

But when I change the Parent object Parent.child1 remains the same.

parent.addr = 'France'

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

You could make Child.addr a property that gets the addr of the parent:

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

Another way of doing this is use addr instead of self.addr in the Parent class.

Example:

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')

Output: parent.child1.addr is 'USA'

parent.addr = 'France'

Output: parent.addr is 'France'

Related