0

I'm trying to merge two instances of two different classes. One idea that could work for me is to assign the attributes from class b to an existing instance of class a. Normally I would let a inherit from b but this is not possible because a is initialized when b is still unknown.

Obviously this is a dummy example, but i think it reflects my problem.

class aa:
    def __init__(self) -> None:
        self.c = 'c'

class bb:
    def __init__(self, obj) -> None:
        obj.get_c = self.get_c
        self.c = 3
    
    @property
    def get_c(self):
        return self.c

a=aa()
b=bb(a)

Is it possible to copy the method get_c that it returns a.c when a.get_c is called and not whatever value b.c had whenb was initialized?

Desired Output:

a.get_c -> 'c'
b.get_c -> 3
Yehla
  • 199
  • 11
  • *"when a.get_c is called"* `a` does not have a `get_c` method, so the answer is no – DeepSpace Mar 19 '21 at 16:42
  • 1
    @DeepSpace That's what he's trying to find out how to do -- he wants to give `a` a `get_c` property by copying it from `b`. – Barmar Mar 19 '21 at 16:43
  • @Barmar I see, but why not just implement it on `a` to begin with? – DeepSpace Mar 19 '21 at 16:45
  • This might be a starting point: https://stackoverflow.com/questions/3681272/can-i-get-a-reference-to-a-python-property – Barmar Mar 19 '21 at 16:45
  • @Yehla This feels like an XY problem. See my previous comment. Why are you not defining the property in `aa`? – DeepSpace Mar 19 '21 at 16:45
  • I tried to do that but it references to yet another class' property which is still `None` at the creation of `b` so it's actually not `self.c` but `self.another_class.c`. And then it still copies the None instead of the later value. – Yehla Mar 19 '21 at 17:09

0 Answers0