3

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 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.