1

Suppose I have two classes, parent and child as shown below:

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

    def change_name(self, name):
        self.name = name

class Parent:
    def __init__(self, child):
        self.child = child
        self.childs = [child]

    def new_child (self, child):
        self.childs.append[child]
        self.child = child

Now if I create child object and parent object, then I want to call child properties from the parent as shown in the example below

child = Child('Nelson')
parent = Parent(child)

# I want to access child name from the parent object

print(parent.name) # should return parant.child.name <'Nelson'>

new_child = Child('Thomas')
parent.new_child(new_child)
print(parent.name) # should return the new name <'Thomas'>

# some code that will change the name of the child object
print(parent.name) # should return the new name

currently, I added a property decorator in the Parent class which returns the child property

class Parent:
    def __init__(self, child):
        self.child = child
        self.childs = [child]

    def new_child (self, child):
        self.childs.append[child]
        self.child = child

    @property
    def name(self):
        return self.child.name

However, my child object has more than one property and I am looking for a more efficient way to inherit child properties into parent object

  • 1
    I don't think "inherit child properties into the parent object" is quite the right terminology. There's no inheritance here--we have horizontally-related classes, not vertically related classes. The child is publicly exposed, so we can go ahead and access all the properties using the extra layer of indirection `parent.child.foo`, `parent.child.baz = "quux"`, etc. If you're trying to encapsulate, that's OK, but it's not clear that that's needed at the moment. See [x-y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) and maybe provide more context here. Thanks! – ggorlen Sep 20 '19 at 00:27

1 Answers1

0

You have outlined the clearest and most accessible to do it:

  • have the parent property call the referenced child objects name property

Another method could be done via metaprogramming, where you intercept __getattribute__ calls on the parent and see if the child hasattr, which you would then return the child property.

See here: Intercept method calls in Python

FelizNaveedad
  • 358
  • 2
  • 7